Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sockets 如何查找已使用的地址?_Sockets_Error Handling_Port_Winsock - Fatal编程技术网

Sockets 如何查找已使用的地址?

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

这是我的代码,可以运行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.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
工具,或通过编程使用