How to Create a TCP socket connect using C to a predefined port
c, sockets, tcp
Solution
The call to bind function will return -1 if there is an error. This includes the case where the address is already in use.
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 12345
int main()
{
struct sockaddr_in addr;
int fd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1)
{
printf("Error opening socket\n");
return -1;
}
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = 0;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
if(bind(fd, (struct sockaddr *)&addr,sizeof(struct sockaddr_in) ) == -1)
{
printf("Error binding socket\n");
return -1;
}
printf("Successfully bound to port %u\n", PORT);
}
Problem
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.