TCP协议,两个socket绑定同个端口,需要使用setsockopt,以为UDP的不用,测试了下,如果第二个socket在bind之前不使用setsockopt,bind函数会返回-1。
如下面的代码
WORD sockVision = MAKEWORD(2, 2);
WSADATA wsadata;
SOCKET sclient;
struct sockaddr_in clientAddr;
char senddata[255];
char revdata[255];
int ret = -1;
int len = -1;
if (WSAStartup(sockVision, &wsadata) != 0)
{
printf("WSA初始化失败\n");
system("pause");
return 0;
}
sclient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sclient == INVALID_SOCKET)
{
printf("socket客户端创建失败\n");
system("pause");
return 0;
}
int port = 7081;
char str[16] = "47.112.212.215";
clientAddr.sin_family = AF_INET;
clientAddr.sin_port = htons(port);
clientAddr.sin_addr.S_un.S_addr = inet_addr(str);
len = sizeof(clientAddr);
SOCKADDR_IN addrClient;
addrClient.sin_family = AF_INET;
addrClient.sin_addr.S_un.S_addr = inet_addr("0.0.0.0"); // 客户端地址 0.0.0.0
addrClient.sin_port = htons(7777); // 客户端为7777端口
BOOL bReuseaddr1 = TRUE;
setsockopt(sclient, SOL_SOCKET, SO_REUSEADDR, (const char*)&bReuseaddr1, sizeof(BOOL));
int clientbind = bind(sclient, (SOCKADDR*)&addrClient, sizeof(SOCKADDR));
printf("clientbind = %d\n", clientbind);
SOCKET serSocket;
struct sockaddr_in remoteAddr;
struct sockaddr_in sin;
int nAddrlen = sizeof(remoteAddr);
//绑定IP和端口
sin.sin_family = AF_INET;
sin.sin_port = htons(7777);
sin.sin_addr.S_un.S_addr = INADDR_ANY;// inet_addr("127.0.0.1")
serSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (serSocket == INVALID_SOCKET)
{
printf("socket服务器创建失败\n");
}
bReuseaddr1 = TRUE;
setsockopt(serSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&bReuseaddr1, sizeof(BOOL));
int serverbind = bind(serSocket, (LPSOCKADDR)&sin, sizeof(sin));
printf("serverbind = %d\n", serverbind);
输出
clientbind = 0
serverbind = 0
如果注释掉第二个setsockopt
输出
clientbind = 0
serverbind = -1