In my project i want to open some port xxxx and need to write data and close that port XXXX.
Again i want to reopen same port and write data and closing. This what my requirement.
For first time i am able to write and close, but for second time binding is not happening. i don't why may be code issue or anything else.
Here is my code.
int main(void)
{
int connection;
int sock = create_socket(40056);
struct sockaddr_in client_address;
int len = sizeof(client_address);
connection = accept(sock, (struct sockaddr*) &client_address,&len);
close(connection);
close(sock);
sock = create_socket(40056);
connection = accept(sock, (struct sockaddr*) &client_address,&len);
}
int create_socket(int port)
{
int sockfd;
struct sockaddr_in servaddr;
int reuse = 1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
PRINTF("socket creation failed...\r\n");
}
else
PRINTF("Socket successfully created..\r\n");
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof reuse);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)))
!=0) //here typedef &servaddr
{
PRINTF("socket bind failed...\r\n");
}
else
PRINTF("Socket successfully binded.. %d\r\n",port);
listen(sockfd, 5);
PRINTF("finished create socket function\r\n");
return sockfd;
}
accept()
blocks as there are no pending connections. The relevant piece from here is:
If no pending connections are present on the queue, and the socket is
not marked as nonblocking, accept() blocks the caller until a
connection is present. If the socket is marked nonblocking and no
pending connections are present on the queue, accept() fails with the
error EAGAIN or EWOULDBLOCK.
You can mark the socket nonblocking with fcntl()
, (optionally) add a call to perror (to get the "Resource temporarily unavailable"), and run your code to see the difference.
#include <fcntl.h>
#include <errno.h>
int create_socket(int port)
{
.
sockfd = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sockfd, F_SETFL, O_NONBLOCK);
.
}
int main(void)
{
.
connection = accept(sock, (struct sockaddr*) &client_address,&len);
if (connection == -1) {
perror("accept");
}
.
}