-
server ip
Im trying to setup a port listening program using c++ with socket.
If I configure my address like this,
Code:
sockaddr_in host;
host.sin_family = AF_INET;
host.sin_port = htons(portnr);
host.sin_addr.S_un.S_addr = inet_addr("10.0.0.10");
memset(&(host.sin_zero), '\0', 8);
inputing my computers ip staticlly I get my server to work. If I however try to use the loop-back address (127.0.0.1) it doesnt work. How can I setup my program to use the computers current ip address ?
Thanks for any help.
-
Well "it doesn't work" is the nice and specific error reporting which doesn't actually help anyone.
How about
a) posting a complete program reduced to show the problem
b) filling what remains with lots of error checking. Every single socket function returns some kind of error.
c) posting what remains here, along with your error diagnostics if you're still stuck.
-
Thanks for your reply Salem. The thing is, I dont get an either a compile error nor a run-time error.
What my server program does is basiclly output to the screen whatever is send to it.
If I compile the server program with the ip 10.0.0.10 (which is my computer ip address) and I then send a msg to that address from another program the server program prints the message onto the screen. This is very nice but not very flexible since the server program is limited to computers using the ip 10.0.0.10.
So like I sayed about, I tryed to set the address to 127.0.0.1 and then run the program, if I then send a message to the server (I still send the message to ip 10.0.0.10 which is the server ip) nothing happens (i.e. it does not print out any message).
The only difference between the two is the ip address.
So my question is bascilly, how can I figure out the ip address on the computer that my server program is running ?
Hope this makes sense, if not please let me know.
Here is the server code,
Code:
int MAX_DGRAM_SIZE = 1024;
char inBuf[MAX_DGRAM_SIZE];
initWinsock(); /* init's the winsock */
if ((id = socket(AF_INET,
SOCK_DGRAM,
IPPROTO_UDP)) == INVALID_SOCKET)
{
return SOCK_ERROR;
}
if(bind(id, reinterpret_cast<sockaddr*>(&host), sizeof(host)) == SOCKET_ERROR)
{
cout << "WSAGetLastError = " << WSAGetLastError() << endl;
return SOCK_ERROR;
}
int len = sizeof(struct sockaddr);
while(1)
{
if(recvfrom(id, inBuf, MAX_DGRAM_SIZE, 0, reinterpret_cast<sockaddr*>(&target), &len) == SOCKET_ERROR)
{
cout << "WSAGetLastError = " << WSAGetLastError() << endl;
return SOCK_ERROR;
}
cout << "Result=" << inBuf << endl;
}
WSACleanup();
return 0;
-
Instead of this:
>>host.sin_addr.S_un.S_addr = inet_addr("10.0.0.10");
Use this:
>>host.sin_addr.s_addr = INADDR_ANY;
-
Thanks for your reply. Your solution seems to work, do you mind telling how is works ?
Just before checking this post I found this code bit that figures out the computers ip address here
-
By using INADDR_ANY, it just tells the socket to listen on any IP addresses that TCP/IP is bound to.
-