What exactly bind API do in Server program [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
what exactly bind api doing in server programm.
I am very new for socket programming.
Bind says : bind the socket to IPaddress and port.
So what exactly happen if i give
argument1 of bind=AF_INET & args2=(sockaddr *)struct sockaddr hint and args3=sizeof(hint);

In short: bind() specifies the address & port on the local side of the connection. If you don't call bind(), the operating system will automatically assign you an available port number.
Each time an IP datagram containing TCP data is sent over the network, the datagram contains a 'local address', 'remote address', 'local port', and 'remote port'. This is the only information that IP has to figure out who ends up getting the packet.
So, both the client and the server port numbers need to be filled in before the connection can work. Data that is directed to the server needs a 'destination' port, so that the data can get sent to the appropriate program running on the server. Likewise, it needs a 'source' so that the server knows who to send data back to, and also so that if there are many connections from the same computer, the server can keep them separate by looking at the source port number.
Since the connection is initiated by the client program, the client program needs to know the server's port number before it can make a connection. For this reason, servers are placed on 'well-known' port numbers. For example, a telnet server is always on port 23. A http server is always on port 80.
The bind() API call assigns the 'local' port number. That is, the port number that is used as the 'source port' on outgoing datagrams, and the 'destination port' on incoming datagrams.
There is a detailed explanation here with an example.

Related

How to avoid re-use socket? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
There is a server, there are clients. Clients connect to the server. Servers function "accept" returns socket connected client. But when the client socket becomes invalid, it can be reused. How to prevent the server to reuse the same socket?
P.S.: For fans downvote pay attention, I'm not asking about a socket server, I ask about a client sockets.
This is just to clear up some misconceptions - I'm still voting for the question to be closed unless it's edited into something sensible.
But when the client socket becomes invalid, it can be reused
No, the socket file descriptor has to be closed if the TCP connection has shut down. A new socket could be allocated later for a new TCP connection, and receive a file descriptor with the same integer value, but it isn't the same socket.
The socket - this is not just a port, but also the address.
No, a socket is the handle your process uses to talk to the OS about a TCP connection, which is itself uniquely identified by the 4-tuple consisting of two ports and two addresses. See this answer, I'm not going to paste it all here.
If no connection, then the customer will not be aware of this [closing a socket]
If there is no connection, there's nothing to close.
If there is an existing TCP connection, and either the client or server close their socket, the other end will be notified, and the other end's socket will also become invalid (and should be closed in response).
For example, socket have parameters SO_REUSEADDR and SO_REUSEPORT. Why would they?
When you close a connection, you send a packet telling the other end of the connection that you've done so. Even after they've acknowledged this, you could receive other packets on the same connection, if they took a different network path. So, TCP keeps the closed connection around in TIME_WAIT state, preventing another connection starting on the same address:port tuple, for some arbitrary time until it's very unlikely to receive a packet that was really intended for the previous connection.
This arbitrary TIME_WAIT duration is 4 minutes, which is easily long enough that you could, for example, kill a server process and then restart it (at which point it will fail to bind to its address:port, because the closed connection is still using that address:port).
SO_REUSEADDR allows the server to replace the old TIME_WAIT connection with its new, live connection.
SO_REUSEPORT allows multiple sockets to bind to, and accept on, the same port for load-balancing purposes.
This is all documented, eg. in the man page, and neither option has anything to do with the socket file descriptor value.
As bolov said in a comment, the reason these are used by the server is that you actually care about the address:port bound by a server, because that's how you know where to reach it. The local port of a client connection is generally assigned from the ephemeral port range, and no-one cares what its value is except that it's unique at that moment in time.
This can be possible by creating such program that on not accepting by the server the socket id file descriptor is released. But this can complicate the OS may be a scenario that OS may failed.
file descriptors for a single process, file table and inode table available. As each file descriptor may be directed by individual inode.
But maximum number of inodes is fixed at file system creation, limiting the maximum number of files the file system can hold. A typical allocation heuristic for inodes in a file system is one percent of total size.
As indoe table has fixed size and on releasing the file descriptor that particular inode is free, but as per your way inode table may be dry up soon and crash the system.

How does dedicated Server notifies Cliens about each other in p2p (TCP) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am learning about network programming and I want to create a simple P2P network based on TCP connection.
So far I have a server that accepts connections from clients (TCP). Clients know about server's initial location.
These are my questions:
How can server notify clients about each other? is it the matter of simply sending a list of every bodies IP addresses to everybody ?
If all clients are running on the same machine (eg 127.0.0.1), do they need to use a different port number when connecting between each other ?
If I want to maintain a TCP connection, how do peers decide who is going to be a client and who is a server in each pair? Perhaps this can be done on server side when he is sending off information out to clients.
I assume that TCP connection is not ideal in this scenario, at least for the reason that clients have to maintain a separate connection for each peer in a network. Although this is more of a training exercise and I looking for a reliable connection, where I don't have to deal with possibility of some packets been lost/out of order. (at this stage:).
Thank you!
For question one it's up to your design, but informing connected clients in regular intervals about other clients is one way to do it.
As for the second question, if a client also should act as a server for other clients, then they have no choice as each client needs to bind to a local address (ip-address/port-number pair) and if one port on a specific ip-address is used then you have to pick another. This can be automated by setting the port to zero when binding, and the operating system will pick a port for you.
As for the third question, why can't a client be both client and server? Clients connect to the central server, which keeps track all clients in the network, and probably also handles queries from clients. When the central server receives a query it sends it to all other connected clients, and replies back to the querying client about what other clients have whatever it searches for. Then the originating client connects to the other clients that have whatever it searched for, and then those clients acts as servers for the original client.
Something like this:
Client A, B, C, and D connects to server
Client A sends query to server
Server sends query on to client B, C and D
Client B and D replies that they have what was queried
Server send the information back to client A
Client A connects to clients B and D
Now clients B and D are acting as both clients and servers. It also solves your first problem, in that the server only send information about other clients when needed.
I think the answer is yes.
You can also use other Linux IPC mechanisms, like shared memory, rather than socket for the clients on the same server
Server/Client role is differentiated when connection is established: server is listening/accepting and client is connecting. After connection is established, they are in peer to peer relation.

Is it possible to create a SYN packet and then trasmit it with the socket send() function? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
So I am currently writing a C++ program that is a peer-to-peer instant messenger. So when the program starts, it listens for incoming connections on a designated port but also will allow the user to initiate a connection to another host by entering their IP address. Now the socket connect() function AFAIK works much like the send() function but it transmits a SYN packet until the server responds with an accept() or if the server rejects the connection is closed down. So the main question is.......If I create a socket and then call the listen() function, will I get an error if I then call the connect function on the same port? If so, is there a way to create a SYN packet and then call the send() function to transmit it to the designated host? This program is a deviation from the client-server model because any host running this program is going to act as both a client AND a server.
A socket can either listen or connect. It can't do both.
If you want each host to be both a client and a server then each will need two sockets.
On MacOS X at least, there's a specific error message for what you're trying to do in the connect(2) man page:
[EOPNOTSUPP] Because socket is listening, no connection is allowed.
Now the socket connect() function AFAIK works much like the send() function but it transmits a SYN packet until the server responds with an accept() or if the server rejects the connection is closed down
That's not correct for a start. connect() sends a SYN all right, but the ACK reply comes from the peer TCP stack, possibly long before the server application gets anywhere near calling accept(). This is because of the listen backlog queue.
So your motivation is already suspect.
If I create a socket and then call the listen() function, will I get an error if I then call the connect function on the same port?
Yes. You can't do that. You haven't motivated this question, but you don't even need to do that. You have no requirement to use the same local port for an outbound connection that you are listening for inbound connections on.
is there a way to create a SYN packet and then call the send() function to transmit it to the designated host?
You can send a SYN manually, if you can work out how to create a raw IP socket, but you can't get TCP/IP to recognize it as part of a TCP connection. Again this has nothing to do with whatever your problem is.
I'm not even convinced you have a problem actually. All you need is a listening socket, accepted sockets, and sockets for outbound connections, all created in the usual way. No tricks required.

How to get the client IP address before accepting the connection in C++

I'm studing c++ socket programming...
The server program binds to a socket and starts listening for connection requests...ok now how can I list the IP addreses of the listened requests?
I know I can get the IP addresses after accepting the connections but lets say I don't wanna accept a connection from an specific IP address...
On Windows only, you can use the conditional callback feature of WinSock2's WSAAccept() function to access client information before accepting a connection, and to even reject the connection before it is accepted.
This can't be done in terms of the standard socket API. On all platforms I know, the system actually accepts the connection (i.e. responds with SYN+ACK TCP datagram) before the application has a chance to monitor the pending request.
For optimum performance, this would be solved by filtering in the network stack, but the details of doing that will depend on the operating system (this is not part of the socket interface and your application may generally not even have the rights to configure your network stack this way.)
The other opportunity is after the accept, by which time the connection is already accepted (CONNECT ACK) on TCP level.
I don't think you can do it in the middle phase where you would prefer that. That however would not be very different from doing it after accept anyway.

How do I create a TCP server that will accept only one connection at a time? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm writing a client-server pair in C++ using Linux sockets. I want the server to listen for a connection, and while one client is connected the server should reject any other clients that try to connect.
I tried implementing this by setting the backlog parameter in the listen function to 0 and to 1 and neither one of those values seems to work. The first client connects as expected, but any subsequent clients just block while the first client finishes. What's really confusing to me is that they don't block on connecting to the server, they block on the first read.
I used the code here to get started writing my client and server. Does anyone know what I need to change to get the server to accept only one client connection, and drop any subsequent connection attempts?
When you accept a connection, a new socket gets created. The old one is still used to listen for future connections.
Since you want to only allow 1 connection at a time, you could just accept the connections, and then close the new accepted socket if you detect you are already processing another.
Is there a net difference that you are looking for compared to closing the new accepted socket right after the accept? The client will know as soon as it tries to use its socket (or right away if it is already waiting on the server with a read call) with a last error of: server actively closed the connection.
Just don't fork() after accept().
This pseudo-C-code will only accept one client at once.
while(1) {
listen()
accept()
*do something with the connection*
close()
}
You could close your original socket that's listening for connections after accepting the first connection. I don't know if the socket class you're using will allow you to do that though.
Sounds like you need to implement it manually. Let a client connect, then send a disconnect message from the server to the client if there's already another client connected. If the client receives this message let it disconnect itself.
Since you want to only allow 1 connection at a time, you could just accept the connections, and then close the new accepted socket if you detect you are already processing another.
I think it should be the listen socket that to be closed.
When the first connection is established, you close the original listen socket.
And after that no more connections can be established.
After the first connection ends, you can create a new socket to listen again.
If you have control over the clients, you can make the sockets non-blocking. In this case they'll return the error message EINPROGRESS.
I'm still looking for how to change the socket to be non-blocking. If anybody know how to offhand, feel free to edit the answer.
let the listening socket die after accepting and starting a new connection. Then when that connection is done, have it spin off a new listening socket.
You might have the socket option TCP_DEFER_ACCEPT set on your listening socket:
TCP_DEFER_ACCEPT (since Linux 2.4)
Allows a listener to be awakened only when data arrives on the socket.
Takes an integer value (seconds), this can bound the maximum number of
attempts TCP will make to complete the connection. This option should
not be used in code intended to be portable.
I would assume it would lead to the effect you described, that the connecting client doesn't block on the connect, but on the subsequent read. I'm not exactly sure what's the options default setting and to what it should be set to disable this behavior, but probably a value of zero is worth a try:
int opt = 0;
setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &opt, sizeof(opt));
As far as I see, it is not possible to listen for exactly one connection.
Tcp involves a 3-way handshake. After the first syn packet is received the kernel puts that "connection" in a wait queue, answers with an syn/ack and waits for the final ack. After this is received it moves the connection from the wait queue to the accept queue, where it can be picked up by the application using the accept() call. (For details have a look here.)
On linux the backlog argument only limits the size of the accept queue. but the kernel will still do the 3-way handshake magic. The client receives syn/ack and answers with the final ack and calls the connection established.
Your only options are, either shutting down the listening socket as soon as you accepted the first connection. (This might however result in other connection already being available.) Or you actively accept other connections and close them immediately to notify the client.
The last option you have is the one you are already using: let the server queue your connections and process them one after the other. Your clients will block in that case.