When I try to bind port 80 to a socket in c, i always get the error, that I don't have permission to use this port. is there an easy way to get this permission?
The bind() function binds a unique local name to the socket with descriptor socket. After calling socket(), a descriptor does not have a name associated with it. However, it does belong to a particular address family as specified when socket() is called. The exact format of a name depends on the address family.
When a socket has both an IP address and a port number it is said to be 'bound to a port', or 'bound to an address'. A bound socket can receive data because it has a complete address. The process of allocating a port number to a socket is called 'binding'.
bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.] connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.
For client programs, it is not required to bind the socket explicitly to a port. The kernel of the operating system takes care of assigning the source IP and a temporary port number. The client socket can use the connect() method, after the socket creation is complete to contact the server socket.
Usually only the superuser (root) can bind to 'privileged' ports (i.e. those port numbers below 1024).
This means that you either have to run your program as root or make your executable 'suid root'.
Both of these have security consequences so you may want to consider using the suid approach and relinquishing superuser privileges once the bind call has been made.
You will find this tutorial very helpful on network programming with C/C++.
And, by the way, ANSI C has no way to access the network. It is the OS supplied libraries (the BSD socket API, also ported to Windows as winsock
) that provide this capability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With