Junaid
Junaid

Reputation: 71

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]));

Upvotes: 3

Views: 526

Answers (4)

nl-x
nl-x

Reputation: 11832

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.

Upvotes: 1

millimoose
millimoose

Reputation: 39950

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.

Upvotes: 0

mah
mah

Reputation: 39807

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.

Upvotes: 3

ybo
ybo

Reputation: 17152

You don't have to, you can use INADDR_ANY instead of the real address, but it can be useful when you have multiple network interfaces on your machine.

Upvotes: 1

Related Questions