Sockets 如何查找已使用的地址?
这是我的代码,可以运行CentOS和Windows,只需修复一些标题Sockets 如何查找已使用的地址?,sockets,error-handling,port,winsock,Sockets,Error Handling,Port,Winsock,这是我的代码,可以运行CentOS和Windows,只需修复一些标题 #define _WIN32_WINNT 0x0501 #include <WinSock2.h> #include <WS2tcpip.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> /* #include <sys/socket
#define _WIN32_WINNT 0x0501
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
/*
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
*/
int main()
{
int sock;
int ret = 0;
int port= 12345;
struct sockaddr_in addr;
char buf[1024];
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock<0){
printf("socket() ret = %d : %s\n",ret,strerror(errno));
return ret;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
if(ret<0){
printf("bind() ret = %d errno =%d : %s\n",ret,errno,strerror(errno));
return ret;
}
printf("############# Binding port %d type Enter to stop \t",port);
fgets(buf,sizeof(buf),stdin);
return 0;
}
[第二proc@centOS]
$ ./udp
bind() ret = -1 errno =98 : Address already in use
$
然而,当我在windows上用相同的代码做相同的事情时,消息是不同的
[第一proc@windows]
C:\ >udp
############# Binding port 12345 type Enter to stop
C:\ >udp
bind() ret = -1 errno =34 : Result too large
C:\ >
[第二proc@windows]
C:\ >udp
############# Binding port 12345 type Enter to stop
C:\ >udp
bind() ret = -1 errno =34 : Result too large
C:\ >
如何获取Windows上已使用的地址?我认为您不应该在Windows上使用
errno
作为套接字代码。您可以尝试使用返回的WSAGetLastError
errno不支持建议的EADDRINUSE
我认为你应该设计一个方案,其中你有一个my_errno
功能,根据平台使用errno
或WSAGetLastError
这个电话可能有一个微妙的问题。参数求值顺序未指定,
strerror
本身可以更改errno
,这意味着它有副作用。在做任何其他事情之前,您应该单独打印errno
。正如cnicular所说,您必须在Windows上使用,而不是errno
。要获取套接字错误代码的文本消息,可以使用
要回答您的问题,如果您想知道谁在使用该端口,可以使用命令行netstat
工具,或通过编程使用