问题
I'm new to networks and I'm wondering why this TCP Server-Client implementation in C only works on one computer? (1)
I mean I have to open one terminal for the server program and another one for the client program. But why this doesn't work between computers? Starting the server program on one computer and the client program on another computer.
How we need to modify the code to work between computers? (2)
And what are great resources to start on the whole topic? (3)
回答1:
It will work on other computers. Just ensure you do the followings:
- Two computer be on a network and see each other with PING
- Change
127.0.0.1
in client program with the IP of the server machine - Check listening ports with
netstat
of server machine and Make sure the port 8080 is in Listening mode - Make sure there is no firewall in server machine, you can use
telnet
in client machine to make sure port on the server is accessible.
Before test your C program, make sure the communication is OK between servers by third party application. For example, make an echo server in linux by ncat -l 2000 -k -c 'xargs -n1 echo'
on port 2000.
It highly recommended change Port from 8080 to another one (for example 8192). 8080 is used with some third party applications.
回答2:
The host used by the client is hardcoded:
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
You can change the host into the code to reach another computer, or you can read it from command line to have a more flexible use.
来源:https://stackoverflow.com/questions/63243439/c-why-does-this-server-client-setup-only-work-inside-one-computer