Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is socket bind and how to bind an address?

In Java, I need to know what is the bind operation:

ServerSocket.bind()

From Javadoc:

Binds the ServerSocket to a specific address (IP address and port number).

I know what is bind and EJB (from example) to a name. Is this similar?

How to bind a local address to a server socket?

I am using:

providerSocket.bind(new InetSocketAddress("192.168.0.1", 0));

And I got Already Bound error!

like image 745
Muhammad Hewedy Avatar asked May 22 '11 21:05

Muhammad Hewedy


People also ask

What is binding a socket to an address?

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'.

What is bind () socket?

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.

How do I bind a UDP socket to an IP address?

You would do this with the bind() function: int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); The first parameter is the file descriptor for the socket. The second is a pointer to a socket address structure which contains (for IPv4 or IPv6) the IP address and port to bind to.


2 Answers

A connection requires a client and a server.

For a client to send data to the server, the client must have the server's address and port number. Similarly, for the server to send data to the client, the server must have the client's address and port number.

Binding a socket means assigning an address and port number to the socket.

When you do:

providerSocket.bind(new InetSocketAddress("192.168.0.1", 0));

You get Already Bound error because providerSocket already has an address and port number, and assigning a new address / port number is not allowed. Once a ServerSocket is created, it is bound (unless it uses the parameterless constructor java.net.ServerSocket.ServerSocket()).

like image 163
Pacerier Avatar answered Oct 19 '22 19:10

Pacerier


you have to leave ServerSocket() blank not ServerSocket(666,9) you should not do the second example or else it wont work. Inside the Parenthesis of the ServerSocket you type nothing.

like image 1
pratham12 Avatar answered Oct 19 '22 20:10

pratham12