Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

sockets

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]));
like image 323
Junaid Avatar asked Dec 21 '25 17:12

Junaid


2 Answers

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.

like image 108
mah Avatar answered Dec 24 '25 05:12

mah


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.

like image 33
ybo Avatar answered Dec 24 '25 05:12

ybo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!