user1739860
user1739860

Reputation:

Sending IP address through socket in C

I currently have a working client (written in C++) and a working server (written in C). I'm currently trying to figure out how to send to the client from the server a message that says "Hello, (Clients IP address)", also I'd like to respond to the client when he says "Hello" with a message of my choosing. Also when the client sends "quit" I'd like to disconnect the client, but not shutdown the server. Below is my code.

 while(true)     // loop forever
 {
  client = accept(sock,(struct sockaddr*)&from,&fromlen);      // accept connections

  unsigned long ulAddr = from.sin_addr.s_addr;

  char *client_ip;
  client_ip = inet_ntoa(from.sin_addr);

  cout << "Welcome, " << client_ip << endl; // usually prints hello %s
  // cout << "client before thread:" << (int) client << endl;
  // create our recv_cmds thread and pass client socket as a parameter
  CreateThread(NULL, 0,receive_cmds,(LPVOID)client, 0, &thread);
 }

 WSACleanup();

updated code* my current problem is that it just prints Welcome %s, not an actual IPv4 address.

Upvotes: 0

Views: 2361

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595329

char welcome[90] = "Welcome %s",inet_ntoa(addr_remote.sin_addr);

You can't format a string buffer in a declaration like that. You need to use sprintf() or similar function instead, eg:

char welcome[90];
sprintf(welcome, "Welcome %s", inet_ntoa(addr_remote.sin_addr));

Or else use a std::string instead:

std::string welcome = "Welcome " + std::string(inet_ntoa(addr_remote.sin_addr));
...
write(nsockfd , welcome.c_str() , welcome.length());

Upvotes: 3

Related Questions