Socket freezes when write is attempted - c

I am writing a FTP server in C. Currently I am struggling with passive connection. I maintain a connection via sockets, and I have two of those. The first one is const int a_socket, it is created when a client connects and it accepts all client commands and sends response codes from the server. The second one is int p_socket, which is only connected when passive mode is requested by the client It is supposed to send large data. I get an error when I try to send anything through p_socket - the server gets stuck in the write function and the client (I am currently testing against Filezilla) recieves ECONNRESET. It also appears that the server is sending RST instead of the message.
I create the sockets with create_socket
int create_socket(int *ap_socket, const int a_port) {
// variables
struct sockaddr_in serverAddr;
int yes = 1;
// create address
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(a_port);
// create socket
if ((*ap_socket = socket(serverAddr.sin_family, SOCK_STREAM, 0)) < 0) {
perror("service_create(): create socket");
return 0;
}
// set options
if (setsockopt(*ap_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) {
perror("service_create(): socket opts");
return 0;
}
// bind socket
if (bind(*ap_socket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
perror("service_create(): bind socket");
close(*ap_socket);
return 0;
}
// listen to socket
if (listen(*ap_socket, SERVER_SOCKET_BACKLOG) < 0) {
perror("service_create(): listen socket");
close(*ap_socket);
return 0;
}
return 1;
}
The client connects without issues on both sockets, but only a_socket is able to send any data. I am using the following function to check the sockets.
int check_socket(const int sd) {
int result = write(sd, "\0", 2);
if (result >= 0) {
return 1;
}
else {
return 0;
}
}
I am using wireshark to view the packets and I do all of the testing on localhost. Socket a_socket connects client
port 43684 to FTP port 21 on server (not seen in the log). Server provides port 20 for passive connection and client connects via port 50601.
Last three lines of the log show results of check_socket. Test message sent from a_socket (\000\000) arrives fine and is ACKned by the client, but the same message sent from p_socket results in RST right on the next line.
I am not fluent in C and I am a beginner in sockets and networking, so any help will be appreciated.

Related

How to handle TCP client disconnect in C

I am trying to write a basic TCP server that streams serial data to a client. The server would connect to a serial device, read data from said device, and then transmit it as a byte stream to the client. Writing the TCP server is no problem. The issue is that the server will crash when a client disconnects. In other languages, like Python, I can simply wrap the write() statement in a try-catch block. The program will try to write to the socket, but if the client has disconnected then an exception will be thrown. In another project, this code snippet worked for me:
try:
client_socket.send(bytes(buf, encoding='utf8'))
except Exception as e:
logger.info("Client disconnected: %s", client_id)
I can handle client disconnects in my C code, but only by first reading from the socket and checking if the read is equal to 0. If it is, then my client has disconnected and I can carry on as usual. The problem with this solution is that my client has to ping back to the server after every write, which is less than ideal.
Does anyone know how to gracefully handle TCP client disconnects in C? My example code is shown below. Thank you!
// Define a TCP socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// Allow for the backlog of 100 connections to the socket
int backlog = 100;
// Supply a port to bind the TCP server to
short port = 9527;
// Set up server attributes
struct sockaddr_in servaddr;
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
// Set the socket so that we can bind to the same port when we exit the program
int flag = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == -1) {
perror("setsockopt fail");
}
// Bind the socket to the specified port
int res = bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
if (res < 0) {
perror("bind fail");
exit(1);
}
// Listen for incoming connections
if (listen(sockfd, backlog) == -1) {
perror("listen fail");
exit(1);
} else {
printf("Server listening on port\n", port);
}
for(;;) {
// Wait for incoming connection
struct sockaddr_in cliaddr;
socklen_t len = sizeof(cliaddr);
int connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &len);
if (-1 == connfd) {
perror("Could not accept incoming client");
continue;
}
//Resolving Client Address
char buff[INET_ADDRSTRLEN + 1] = {0};
inet_ntop(AF_INET, &cliaddr.sin_addr, buff, INET_ADDRSTRLEN);
uint16_t cli_port = ntohs(cliaddr.sin_port);
printf("connection from %s, port %d\n", buff, cli_port);
for(;;) {
// Read from serial device into variable here, then send
if(send(connfd, "Data...Data...Data\n", 19, 0) < 0) {
printf("Client disconnected...\n");
break;
}
}
}
Looks like a duplicate of this, this and this.
Long story short you can't detect the disconnection until you perform some write (or read) on that connection. More exactly, even if it seems there is no error returned by send, this is not a guarantee that this operation was really sent and received by the client. The reason is that the socket operations are buffered and the payload of send is just queued so that the kernel will dispatch it later on.
Depending on the context, the requirements and the assumptions you can do something more.
For example, if you are under the hypothesys that you will send periodic message at constant frequency, you can use select and a timeout approach to detect an anomaly.
In other words if you have not received anything in the last 3 minutes you assume that there is an issue.
As you can easily found, this and this are a good read on the topic.
Look at that for a far more detailed explanation and other ideas.
What you call the ping (intended as a message that is sent for every received packet) is more similar to what is usually known as an ACK.
You only need something like that (ACK/NACK) if you also want to be sure that the client received and processed that message.
Thanks to #emmanuaf, this is the solution that fits my project criteria. The thing that I was missing was the MSG_NOSIGNAL flag, referenced here.
I use Mashpoe's C Vector Library to create a new vector, which will hold all of my incoming client connections.
int* client_array = vector_create();
I then spawn a pthread that continually reads from a serial device, stores that data in a variable, and then sends it to each client in the client list
void* serve_clients(int *vargp) {
for(;;) {
// Perform a microsleep
sleep(0.1);
// Read from the Serial device
// Get the size of the client array vector
int client_vector_size = vector_size(vargp);
for(int i = 0 ; i < client_vector_size ; i++) {
// Make a reference to the socket
int* conn_fd = &vargp[i];
/*
In order to properly handle client disconnects, we supply a MSG_NOSIGNAL
flag to the send() call. That way, if the client disconnects, we will
be able to detect this, and properly remove them from the client list.
Referenced from: https://beej.us/guide/bgnet/html//index.html#sendman
*/
if (send(*conn_fd, "Reply from server\n", 18, MSG_NOSIGNAL) < 0) {
printf("Client disconnected...\n");
// Close the client connection
close(*conn_fd);
// Remove client socket from the vector
vector_remove(vargp, i);
// Decrement index and client_server_size by 1
i--;
client_vector_size--;
}
}
}
}
To spawn the pthread:
// Spawn the thread that serves clients
pthread_t serving_thread;
pthread_create(&serving_thread, NULL, serve_clients, client_array);
When a new connection comes in, I simply add the new connection to the client vector
while(1) {
// Wait for incoming connection
struct sockaddr_in cliaddr;
socklen_t len = sizeof(cliaddr);
int connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &len);
if (-1 == connfd) {
perror("Could not accept incoming client");
continue;
}
//Resolving Client Address
char buff[INET_ADDRSTRLEN + 1] = {0};
inet_ntop(AF_INET, &cliaddr.sin_addr, buff, INET_ADDRSTRLEN);
uint16_t cli_port = ntohs(cliaddr.sin_port);
printf("connection from %s:%d -- Connfd: %d\n", buff, cli_port, connfd);
// Add client to vector list
vector_add(&client_array, connfd);
}
In the end, we have a TCP server that can multiplex data to many clients, and handle when those clients disconnect.

TCP based hole punching

I've been attempting TCP hole punching for a while now and forums don't seem be helping much when it comes to TCP based approach and C programming language. Following were the main references from internet,
a. http://www.brynosaurus.com/pub/net/p2pnat/
b. https://wuyongzheng.wordpress.com/2013/01/31/experiment-on-tcp-hole-punching/
My setup is
Client A -- NAT-A -- Internet -- NAT-B -- Client B.
Assuming that client A knows B's public and private endpoint, and B knows A's endpoints ( I have written a server 'S' that exchanges endpoint information among peers), and given that both the NATs are NOT symmetric, will it suffice (to achieve TCP hole punching), if both the clients attempt to connect() to each other's public endpoint ( for the above setup) repeatedly?
If not, what exactly has to be done to achieve tcp hole punching?
I have two threads on each clients , one that makes a connect call repeatedly to other client, and the other that listens to incoming connection from other client. I have made sure that sockets in both the threads are bound to the local port that was given to the peer. Also, I see that both the NATs preserve port mapping i.e., local and public ports are same. Yet, my program isn't working.
Is it so that the rendezvous server 'S' that I mentioned above has a role to play in punching a hole or creating a NAT mapping that will allow SYN requests to pass through, to the peers. If yes, what has to be done?
Relevant sections of the code are attached.
connect_with_peer() is the entry point, after server 'S' provides the peer's public ip:port tuple, which is given to this function along with local port to which binding is done. This function spawns a thread ( accept_handler() ) which also binds to the local port and listens for incoming connection from the peer.
connect_with_peer() returns a socket , if connect() [ main thread ] or accept() [ child thread ], is successful.
Thanks,
Dinkar
volatile int quit_connecting=0;
void *accept_handler(void *arg)
{
int i,psock,cnt=0;
int port = *((int *)arg);
ssize_t len;
int asock,opt,fdmax;
char str[BUF_SIZE];
struct sockaddr_in peer,local;
socklen_t peer_len = sizeof(peer);
fd_set master,read_fds; // master file descriptor list
struct timeval tv = {10, 0}; // 10 sec timeout
int *ret_sock = NULL;
struct linger lin;
lin.l_onoff=1;
lin.l_linger=0;
opt=1;
//Create socket
asock = socket(AF_INET , SOCK_STREAM, IPPROTO_TCP);
if (asock == -1)
{
fprintf(stderr,"Could not create socket");
goto quit_ah;
}
else if (setsockopt(asock, SOL_SOCKET, SO_LINGER, &lin,
(socklen_t) sizeof lin) < 0)
{
fprintf(stderr,"\nTCP set linger socket options failure");
goto quit_ah;
}
else if (setsockopt(asock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt,
(socklen_t) sizeof opt) < 0)
{
fprintf(stderr,"\nTCP set csock options failure");
goto quit_ah;
}
local.sin_family = AF_INET; /* host byte order */
local.sin_port = htons(port); /* short, network byte order */
local.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
bzero(&(local.sin_zero), 8); /* zero the rest of the struct */
fprintf(stderr,"\naccept_handler: binding to port %d",port);
if (bind(asock, (struct sockaddr *)&local, sizeof(struct sockaddr)) == -1) {
perror("accept_handler bind error :");
goto quit_ah;
}
if (listen(asock, 1) == -1) {
perror(" accept_handler listen");
goto quit_ah;
}
memset(&peer, 0, sizeof(peer));
peer.sin_addr.s_addr = inet_addr(peer_global_address);
peer.sin_family = AF_INET;
peer.sin_port = htons( peer_global_port );
FD_ZERO(&master); // clear the master and temp sets
FD_SET(asock, &master);
fdmax = asock; // so far, it's this one
// Try accept
fprintf(stderr,"\n listen done; accepting next ... ");
while(quit_connecting == 0){
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, &tv) == -1) {
perror("accept_handler select");
break;
}
// run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) { // we got one!!
if (i == asock) {
// handle new connections
psock = accept(asock, (struct sockaddr *)&peer, (socklen_t*)&peer_len);
if (psock == -1) {
perror("accept_handler accept");
} else {
fprintf(stderr,"\n Punch accept in thread succeeded soc=%d....",psock);
quit_connecting = 1;
ret_sock = malloc(sizeof(int));
if(ret_sock){
*ret_sock = psock;
}
}
}
}
} // end for
}
quit_ah:
if(asock>=0) {
shutdown(asock,2);
close(asock);
}
pthread_exit((void *)ret_sock);
return (NULL);
}
int connect_with_peer(char *ip, int port, int lport)
{
int retval=-1, csock=-1;
int *psock=NULL;
int attempts=0, cnt=0;
int rc=0, opt;
ssize_t len=0;
struct sockaddr_in peer, apeer;
struct sockaddr_storage from;
socklen_t peer_len = sizeof(peer);
socklen_t fromLen = sizeof(from);
char str[64];
int connected = 0;
pthread_t accept_thread;
long arg;
struct timeval tv;
fd_set myset;
int so_error;
struct linger lin;
lin.l_onoff=1;
lin.l_linger=0;
opt=1;
//Create socket
csock = socket(AF_INET , SOCK_STREAM, IPPROTO_TCP);
if (csock == -1)
{
fprintf(stderr,"Could not create socket");
return -1;
}
else if (setsockopt(csock, SOL_SOCKET, SO_LINGER, &lin,
(socklen_t) sizeof lin) < 0)
{
fprintf(stderr,"\nTCP set linger socket options failure");
}
#if 1
else if (setsockopt(csock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt,
(socklen_t) sizeof opt) < 0)
{
fprintf(stderr,"\nTCP set csock options failure");
}
#endif
quit_connecting = 0;
///////////
if( pthread_create( &accept_thread , NULL , accept_handler , &lport) < 0)
{
perror("could not create thread");
return 1;
}
sleep(2); // wait for listen/accept to begin in accept_thread.
///////////
peer.sin_family = AF_INET; /* host byte order */
peer.sin_port = htons(lport); /* short, network byte order */
peer.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
bzero(&(peer.sin_zero), 8); /* zero the rest of the struct */
fprintf(stderr,"\n connect_with_peer: binding to port %d",lport);
if (bind(csock, (struct sockaddr *)&peer, sizeof(struct sockaddr)) == -1) {
perror("connect_with_peer bind error :");
goto quit_connect_with_peer;
}
// Set non-blocking
arg = fcntl(csock, F_GETFL, NULL);
arg |= O_NONBLOCK;
fcntl(csock, F_SETFL, arg);
memset(&peer, 0, sizeof(peer));
peer.sin_addr.s_addr = inet_addr(ip);
peer.sin_family = AF_INET;
peer.sin_port = htons( port );
//Connect to remote server
fprintf(stderr,"\n Attempting to connect/punch to %s; attempt=%d",ip,attempts);
rc = connect(csock , (struct sockaddr *)&peer , peer_len);
if(rc == 0){ //succeeded
fprintf(stderr,"\n Punch Connect succeeded first time....");
} else {
if (errno == EINPROGRESS) {
while((attempts<5) && (quit_connecting==0)){
tv.tv_sec = 10;
tv.tv_usec = 0;
FD_ZERO(&myset);
FD_SET(csock, &myset);
if (select(csock+1, NULL, &myset, NULL, &tv) > 0) {
len = sizeof(so_error);
getsockopt(csock, SOL_SOCKET, SO_ERROR, &so_error, (socklen_t *)&len);
if (so_error == 0) {
fprintf(stderr,"\n Punch Connect succeeded ....");
// Set it back to blocking mode
arg = fcntl(csock, F_GETFL, NULL);
arg &= ~(O_NONBLOCK);
fcntl(csock, F_SETFL, arg);
quit_connecting=1;
retval = csock;
} else { // error
fprintf(stderr,"\n Punch select error: %s\n", strerror(so_error));
goto quit_connect_with_peer;
}
} else {
fprintf(stderr,"\n Punch select timeout: %s\n", strerror(so_error));
}
attempts++;
}// end while
} else { //errorno is not EINPROGRESS
fprintf(stderr, "\n Punch connect error: %s\n", strerror(errno));
}
}
quit_connect_with_peer:
quit_connecting=1;
fprintf(stderr,"\n Waiting for accept_thread to close..");
pthread_join(accept_thread,(void **)&psock);
if(retval == -1 ) {
if(psock && ((*psock) != -1)){
retval = (*psock); // Success from accept socket
}
}
fprintf(stderr,"\n After accept_thread psock = %d csock=%d, retval=%d",psock?(*psock):-1,csock,retval);
if(psock) free(psock); // Free the socket pointer , not the socket.
if((retval != csock) && (csock>=0)){ // close connect socket if accept succeeded
shutdown(csock,2);
close(csock);
}
return retval;
}
First, read this very similar question:
TCP Hole Punching
And read the part after EDIT2 (excerpt here). That's possibly the cause of failure.
Once the second socket has successfully bound, the behavior for all
sockets bound to that port is indeterminate.
Don't worry linux has similar limitations in socket(7) with SO_REUSEADDR:
For AF_INET sockets this means that a socket may bind, except when
there is an active listening socket bound to the address. When the
listening socket is bound to INADDR_ANY with a specific port then it is
not possible to bind to this port for any local address
I don't think that listening after instead of before will make a difference.
You don't have to try and open twice your connection.
Summary of steps to establish a TCP connection:
Left side: (a client C connecting to a server S) is the usual case, right side is the simultaneous connection of two peers A and B (what you're trying to do):
C A B
\ (SYN) \ /
\ (SYN)\ /(SYN)
> S X
/ / \
/(SYN+ACK) / \
/ A < > B
C< \ /
\ (SYN+ACK)\ / (SYN+ACK)
\(ACK) X
\ / \
\ / \
> S A < > B
ESTABLISHED ESTABLISHED
references:
https://www.rfc-editor.org/rfc/rfc793#section-3.4 figure 8.
correction for fig 8 line 7:
https://www.rfc-editor.org/rfc/rfc1122#page-87 (section 4.2.2.10)
The difference is the simultaneous SYN2/SYN+ACK2 instead of SYN/SYN+ACK/ACK (in my tests with two linux peers, usually only the "first" answers with SYN+ACK because it's never that simultaneous. It doesn't really matter).
Both peers actively initiate a connection. They're not initially waiting for a connection and you don't have to call listen()/accept() at all. You don't have to use any threads at all.
Each peer should exchange (through S) their intended local port for the other to use (and with the help of S they'll exchange their public IP), with the assumption the port won't be translated.
Now you just try and connect with your 4-uple of informations. each will binds with (INADDR_ANY,lport) and connect to (peer_global_address,peer_global_port) while simultanously B does the same. At the end there is an UNIQUE connection established between both sides.
both NAT boxes will see outgoing packets and prepare a reverse path.
Now what can go wrong?
A NAT box can't cope with the expected packet having a SYN instead of the more common SYN+ACK. Sorry, if that happens you might be out of luck. TCP protocol allows for this case and it's mandatory (rfc 1122 section 4.2.2.10 above). If the other NAT box is fine it should still work (once a SYN+ACK is sent back).
A NAT device (from a peer doing the request too late, say NAT-B in front of B) answers with a RST packet instead of silently dropping the still unknown packet like most NAT devices are doing. A receives RST and aborts the connection. Then B sends it and a similar fate happens. The faster the ping round-trip, the easier you'd get this. To avoid this, either:
if you can control one of the NAT devices, have it drop the packet instead of sending a RST.
be really synchronized (use NTP, exchange a precise date in sub-milliseconds of intended action between the peers through S, or wait the next multiple of 5 seconds to start)
drop the outgoing RST packet with a custom (and temporary) firewall rule on A and/or B (better than dropping the incoming RST, because the NAT devices can decide to close the expectation when they see it)
I can just tell I could have TCP hole punching working reliably "by hand" simply using netcat between two peers set like in your case.
Eg on Linux with netcat: type simultaneously those on the two peers A and B each in a private LAN behind their NAT device. With usual NAT devices (which drop unknown packets), no need for any perfect synchronization, even 5s between those two commands is fine (of course the first will be waiting):
host-a$ nc -p 7777 public-ip-host-b 8888
host-b$ nc -p 8888 public-ip-host-a 7777
When it's done, both netcat have established the SAME UNIQUE connection together, there aren't two connections established. No retry (no loop) was needed. Of course the programs will have used a connect(), and the OS may have sent multiple SYN packets as an automatic retry mechanism during the connect() if the second command (and thus connect() ) is delayed. This is at system/kernel level, not at your level.
I hope this helped so you can simplify your program and have it work. Remember, no need to listen(), accept(), having to fork, use threads. You don't even need a select(), just have connect() block normally without O_NONBLOCK.

local linux socket receives old data

I just wrote a program that uses local socket to communicate between two processes
if client send one message to server, and then close the connection, server would only receive one message
clent:
send(srvfd,data,size,0)
close(srvfd)
server:
n=recv(fd,buf,size,0)
however, if client send one message, and server also send one message (any string) back to client, then client close the connection, server would receive the older message that client sends
client:
send(srvfd,data,size,0)
n=recv(srvfd,buf,size,0)
close(srvfd)
server:
n=recv(fd,buf,size,0)
send(fd,"response",8,0)
n=recv(fd,buf,size,0) //receive the first message again
here is my initialize code:
struct sockaddr_un srvAddr;
int listenFd = socket(PF_UNIX, SOCK_STREAM, 0);
if (listenFd < 0) {
perror("cannot create communication socket");
throw runtime_error("cannot create communication socket");
}
srvAddr.sun_family = AF_UNIX;
strncpy(srvAddr.sun_path, sockFile.c_str(), sockFile.size());
unlink(sockFile.c_str());
int ret = bind(listenFd, (struct sockaddr*) &srvAddr, sizeof(srvAddr));
if (ret == -1) {
perror("cannot bind server socket");
close(listenFd);
unlink(sockFile.c_str());
throw runtime_error("cannot bind server socket");
}
ret = listen(listenFd, BACKLOG);
if (ret < 0) {
perror("cannot listen the client connect request");
close(listenFd);
unlink(sockFile.c_str());
throw runtime_error("cannot listen the client connect request");
}
send(fd,"response",8,0)
n=recv(fd,buf,size,0) //receive the first message again
No you didn't. What you got got was n == 0, meaning end of stream. It also means that zero bytes were transferred into the buffer, so none of what's now in the buffer is now meaningful.
Don't ignore return codes.

segmentation fault with accept() on linux

I have a problem with a client/server programm on linux.
I wrote a server programm wich is sending data cyclic to one conneted client.
Now I want to detect, if the client close the connection to the server. When the connection is closed from the client, i want to wait with accept(...) for an new connection.
Here the critical parts of my code:
error = send(client_sock, Zeichen, 1, MSG_NOSIGNAL);
if(error < 0)
{
connected = 0;
printf("Error, write on TCP Socket failed!!! Reconnecting... \r\n");
close(serverSocket);
initServer();
}
int initServer(void)
{
int *new_sock;
socklen_t size;
struct sockaddr_in server, client;
serverSocket = socket(AF_INET , SOCK_STREAM , 0); //Create socket
if (serverSocket == -1)
{
printf("Could not create socket \r\n");
return 0;
}else
{
printf("Socket created \r\n");
}
server.sin_addr.s_addr = inet_addr(IPAdresse);
server.sin_family = AF_INET;
server.sin_port = htons(TCPPort);
if(bind(serverSocket,(struct sockaddr *)&server , sizeof(server)) < 0)
{
printf("bind failed. Error \r\n");
return 0;
}else
{
printf("bind done \r\n");
}
listen(serverSocket, 1);
printf("Waiting for incoming connections... \r\n");
size = sizeof(sockaddr_in);
printf("size of sockaddr_in: %i \r\n", size);
client_sock = accept(serverSocket, (struct sockaddr *)&client, &size);
if (client_sock < 0)
{
printf("accept failed \r\n");
return 0;
}else
{
connected = 1;
return 1;
}
}
The first time it works fine, I can connect and can send data over the socket. When the client close the connection the error is detected, I close the socket an start the server again to wait for a new connection. But than I get a segmentation fault when I do the accept(..) for the second time!!!
Can someone help me please!!! Thanks a lot!
It's not clear what you're doing when the client connection closes. I see no loop in your code, and yet you're suggesting that accept() is called more than once.
Without seeing the rest or the code, I can only speculate that:
you're repeatedly calling initServer(), hence attempting to recreate the same server socket over and over (which, of course, would be bad),
or
you're calling accept() again somewhere else in your code, most likely with corrupt arguments.
At the very least, what your server-side code should do is initialize the server socket once, then loop around accept(), like so:
call socket() once
call bind() once
call listen() once
then in a loop:
call accept(), this call will block until a client connects, and then return a connected socket,
do whatever you need to do with that (connected client) socket
resume with the loop

why it can be "bad file number" when i write to socket

I have a problem with sending message to server socket from client.
write function returns error - bad file number. It means that I haven't permission to write to this socket.
But from another client I can write to this socket, and do it successfully.
Most interesting, that when another client connected to server my(problem) client can send message too.
the code of my client:
SOCKET OnceCommand;
struct sockaddr_in SAddress4;
struct autoC
{
char buf[4];
short fromx;
short fromy;
short tox;
short toy;
char step;
char cycle;
};
union autocomm{
char byte[14];
struct autoC command;
} Command1, Command2;
memset(&SAddress4,0,sizeof(SAddress4));
SAddress4.sin_family = AF_INET;
SAddress4.sin_port = htons(444);
SAddress4.sin_addr.s_addr = inet_addr(RobotsIP[Robot1]);
memset(&(SAddress4.sin_zero),0,8);
if((OnceCommand = socket(AF_INET,SOCK_STREAM,0))!=SOCKET_ERROR)
{
Err(OnceCommand);
if(conn = connect(OnceCommand,(struct sockaddr *)&SAddress4,sizeof(struct sockaddr))!=SOCKET_ERROR)
{
rc = write(OnceCommand,(char*)Command1.byte,sizeof(Command1.byte));
if(rc < 0)
{
perror("Client-write() error");
rc = getsockopt(OnceCommand, SOL_SOCKET, SO_ERROR, &temp, &length);
if(rc == 0)
{
Err(OnceCommand);
perror("SO_ERROR was");
}
closesocket(OnceCommand);
}
else
{
adv_printf("Client-write() is OK\n");
adv_printf("String successfully sent lol!\n");
}
shutdown(OnceCommand,2);
closesocket(OnceCommand);
}
}
in SO_ERROR was "bad file number"
I'm using sockets lib in ADAM-5510 microcontroller based with ROM-DOS.
I tried to solve this problem by using NONBLOCKing sockets, but select returns only read ready flag.
You are using 0 for the protocol. What is this supposed to be? If TCP, try using IPPROTO_TCP in the socket call, ie.
OnceCommand = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
The problem was not in client part of program. May be by the reason of using advantech socket library or another server program accepted clients' connect, but has no data to read. When i modified server program to receive data only by select it starts work fine.

Resources