tags:

views:

5253

answers:

4

Hi,

I have a very simple question. I want to test whether a particular port is currently under use or not. For this, I want to bind a TCP socket to the port, if the connection is refused means the port is in use and if not that mean the port is free.

Can someone please tell me how can I write the TCP socket code in C? I am on a solaris platform.

I know its very basic. But I appreciate your help. Thanks in advance.

A: 

You might want to look at the source code of netstat. I believe there is a netstat in Solaris as well.

Anonymous
+5  A: 

The call to bind function will return -1 if there is an error. This includes if the address is already in use.

struct sockaddr_in sin;
int socket;

socket = socket(AF_INET, SOCK_STREAM, 0));
if(socket == -1)
{
    printf("error opening socket");
    return -1;
}

sin.sin_port = htons(port);
sin.sin_addr.s_addr = 0;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_family = AF_INET;

if(bind(socket, (struct sockaddr *)&sin,sizeof(struct sockaddr_in) ) == -1)
{
    printf("error binding socket");
    return -1;
}
Joel Cunningham
A: 

Do you just want to test if the particular port is currently in use? (and don't really need to make a program). If so, you can use telnet:

telnet host port

If the connection fails, it's not in use. If it connects and waits for input from you, it's in use :)

moogs
This will only tell you if there is a listening socket on that port, not whether it's open.
Andrew Edgecombe
+4  A: 
Andrew Edgecombe