I am currently implementing a C program which schould send a test string to the HDFS cluster by using the Winsock2 library. The HDFS listens on Port 9999 and the IP-Address is 10.32.0.91 (I use this IP-Address to connect to the HDFS shell via Putty). If the HDFS receives something on Port 9999, it automatically writes it into a test file.
So for example: If I send the string "hello" to the port 9999, HDFS will write "hello" into the testfile.
But it seems that my application is having some trouble on sending this string. In the following you can see the code:
#include <stdio.h>
#include <stdlib.h>
// for networking
#include <Windows.h>
#include <winsock2.h>
int startWinsock() {
WSADATA wsa;
return WSAStartup(MAKEWORD(2, 0), &wsa);
}
int main(int argc, char **argv){
// Initialising Winsock
long rc;
rc = startWinsock();
if(rc != 0) {
printf("Error: startWinsock, error code: %d\n", rc);
return EXIT_FAILURE;
} else {
printf("Winsock has started!\n");
}
printf("Initialised.\n");
// Create socket
SOCKET s;
if((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
printf("Socket created.\n");
// Connect to remote server
struct sockaddr_in hdfs_server;
memset(&hdfs_server, 0, sizeof(hdfs_server));
hdfs_server.sin_addr.s_addr = inet_addr("10.32.0.91");
hdfs_server.sin_family = AF_INET;
hdfs_server.sin_port = htons(9999);
// bind socket to local address and port
if((bind(s, (struct sockaddr *)&hdfs_server, sizeof(hdfs_server)) < 0)){
perror("Error:bind failed!");
return EXIT_FAILURE;
}
// send string
char *sendbuf = "Hello";
send(s, sendbuf, (int)strlen(sendbuf), 0);
return 0;
}
When executing this code, I get the following output in the command prompt:
What am I doing wrong here? The IP-address must be correct because I can connect via putty by entering this IP-address. Any suggestions? Any help is highly appreciated!
You are trying to bind your socket locally to an IP address that does not belong to the local machine, that is why you are getting an "invalid argument" error from bind()
.
Since you are writing a client and not a server, you need to use connect()
instead of bind()
:
// Connect to remote server
struct sockaddr_in hdfs_server;
memset(&hdfs_server, 0, sizeof(hdfs_server));
hdfs_server.sin_addr.s_addr = inet_addr("10.32.0.91");
hdfs_server.sin_family = AF_INET;
hdfs_server.sin_port = htons(9999);
if(connect(s, (struct sockaddr *)&hdfs_server, sizeof(hdfs_server)) < 0){
perror("Error:connect failed!");
return EXIT_FAILURE;
}