简体   繁体   中英

In socket programming in c,why to specify the socket address in server program?

In socket programming in c,why to specify the socket address in server program? Im unable to understand why to specify socket address in server program because socket address we anyways specify in client program,what is the need to specify in server program.

Here is the code:

bzero((char *)&serv_addr,sizeof(serv_addr));

serv_addr.sin_family=AF_INET;

serv_addr.sin_addr.s_addr=inet_addr(argv[1]);

serv_addr.sin_port=htons(atoi(argv[2]));

Most servers don't specify the socket address explicitly, they use INADDR_ANY (as @ybo addresses).

The reason a server might specify the address, however, is to control which interface clients arrive on. For example, you might bind to the address 127.0.0.1 (localhost) to ensure that clients are running on the local machine only, reducing a security risk associated with remote connections. You also might bind explicitly to an external port in order to better sandbox remote clients.

没有 ,你可以使用INADDR_ANY而不是真正的地址,但是当你有你的机器上有多个网络接口,它可以很有用。

Actually same answer as the rest, but in other words:

A server usually just uses 1 public IP address. And also has 1 or more internal IP addresses (like localhost 127.0.0.1 and maybe for lan 192.168.0.1).

But a server can easily also have multiple public IP addresses. Your hosting provider will give these to you (and may be charge you for them.)

A server even NEEDS multiple public IP addresses if it will host multiple HTTPS certificates on port 443, as each one is bound to a specific IP address.

When listening , you can listen on 1 specific IP address, and thus ingore traffic from the other IP addresses. You can even have other applications use the same port number on the other IP adresses.

If for security reasons you only want applications to connect from localhost (eg client and server are on the same machine), you are better off listening only on 127.0.0.1 rather than ALL ip's.

Your computer may have many IP addresses. (Even 127.0.0.1 can be thought of as a separate IP from your "real" one.) On the server socket you can choose which of these addresses you're "listening" to. Following the above example, I believe that binding a server socket to 127.0.0.1 means you'll only be able to connect to that server program locally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM