Nimjox
Nimjox

Reputation: 1381

Socket connection from compiled c.cgi

On linux I want to connect to a demon, via a socket in a compiled c.cgi program (cgic), which is listening for incoming socket connections. I know the server works because it will responded to 'nc' commands. Assume the server is black-boxed, I can't change it. In my client program I have:

int sockfd;
int len;
struct sockaddr_in address;
int result;
char ch[] = "get=DeviceNo";

sockfd = socket(AF_INET, SOCK_STREAM, 0);

address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = 3042;
len = sizeof(address);
result = connect(sockfd, (struct sockaddr *) &address, len);

Which returns with a "Connection Refused" error at this point. As a test I compiled the netcat into the .cgi program which does work:

system("echo '-r get=DeviceNo' | nc localhost 3042");

Am I missing something maybe how the socket class is handled within a .cgi? What should I do to try and get this socket to connect or what can I do to further troubleshoot my problem?

Upvotes: 1

Views: 245

Answers (1)

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

When working with sockaddr_in type, you need to know that both socket address sin_addr.s_addr and port sin_port must be in network byte order. Most likely your host is little-endian.

So you need to use inet_addr returns correct value, but for the socket address you need to use:

address.sin_port = htons(3042);

Upvotes: 2

Related Questions