Question

This is my code which can run CentOS and Windows just fixing some headers.

#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;
}

When I tried to bind same port by this program with runing tow process, there must be the messages that Address already in use like below.

[The first proc@centOS ]

$ ./udp
#############  Binding port 12345 type Enter to stop

[The second proc@centOS]

$ ./udp
bind()  ret = -1 errno =98 : Address already in use
$

However when I do same thing with same code on windows, message is different.

[The first proc@windows]

C:\ >udp
#############  Binding port 12345 type Enter to stop

[The second proc@windows]

C:\ >udp
bind()  ret = -1 errno =34 : Result too large

C:\ >

How can I get Address already in use on Windows?

Was it helpful?

Solution

I don't think you should use errno on windows for sockets code. You could try to use WSAGetLastError which returns WSAEADDRINUSE.

The MSDN page for errno suggests EADDRINUSE is not supported for errno.

I think you should devise a scheme where you have a my_errno function that depending on the platform uses errno or WSAGetLastError.


printf("socket() ret = %d : %s\n",ret,strerror(errno));

There may be a subtle issue with this call. The order of argument evaluation is unspecified and strerror itself can change errno, which means it has side-effects. You should print errno separately, before doing anything else.

OTHER TIPS

Like cnicular said, you have to use WSAGetLastError() on Windows, not errno. To get a text message for a socket error code, you can use FormatMessage().

To answer your question, if you want to find out who is using the port, you can use the command-line netstat tool, or programmably using GetTcpTable2().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top