0

I use socket connection to create client-server program. The server code have to wait for connection from client ip address.

server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("192.168.1.6");  //client ip address

Can I get connection from any ip address not specific ip address to 192.168.1.6 ?

user58519
  • 363
  • 3
  • 13
  • 2
    Look at this: https://stackoverflow.com/questions/21367046/what-is-servaddr-sin-addr-s-addr-inaddr-any and this: https://stackoverflow.com/questions/16508685/understanding-inaddr-any-for-socket-programming – Jerry Jeremiah Feb 27 '20 at 02:38
  • You are mistaken. The bind-address isn't a client address, it is a local address you are listening *at,* for connections from anyone who can reach that address. – user207421 Feb 27 '20 at 05:40

1 Answers1

0

The address you specify isn't the client's IP address, it's the address of the interface on your own host that it's going to listen on.

So, to listen only on localhost, you specify 127.0.0.1. To listen on the external interface that the outside world can see, you can specify that address.

Or, you can specify an address of 0.0.0.0, so a client can connect via any available interface.

Note that although it may initially seem a little crazy, it can actually make perfect sense to listen only on localhost. This lets you "cheat" a little bit on security. Instead of trying (and most likely failing) to do security on your own, an outside user forms an SSH tunnel to your computer, then has their client connect to your server through that tunnel. Your server only has to do its thing, and leaves all the authentication, privacy, etc., to SSH.

Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035
  • Correction. Listening on 192.168.1.1 is not 'listen[ing] only on localhost'. That would be listening on 127.0.0.1. It is listening to the entire subnet and anyone else who can reach it. – user207421 Feb 27 '20 at 05:39
  • @user207421: Oops, quite right about localhost, of course. Listening on 192.168.1.1 would depend. If you configured the network so that was really your host's address, then all would proceed normally. If (as would more often be the case) that was a router's address, then it wouldn't work at all. Doing a quick check, attempting to bind to that address fails. – Jerry Coffin Feb 27 '20 at 09:50