My question is:
Server will create a socket, bind to a given port and with address = INADDR_ANY.
listen() & accept() the new connection. Then, we can get the client's ip-address
from accept().
Now, I want to know the ip-address of the Server, since the host of the server has
multiple NIC on it.
How to know the ip-address of the network interface with which the accepted in-bound socket is from?
I tried getsockname, it gave me the port number, but the ip is all-zero.
Update: Here is the code:
Server.c (header files are removed)
int main(void)
{
struct sockaddr_in stSockAddr;
int res, addr_len, SocketFD, ConnectFD;
struct sockaddr_in addr;
SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(-1 == SocketFD)
{
perror("can not create socket");
//exit(EXIT_FAILURE);
return -1;
}
memset(&stSockAddr, 0, sizeof stSockAddr);
stSockAddr.sin_family = AF_INET;
stSockAddr.sin_port = htons(49335);
stSockAddr.sin_addr.s_addr = INADDR_ANY;
if(-1 == bind(SocketFD,(struct sockaddr *)&stSockAddr, sizeof stSockAddr))
{
perror("error bind failed");
close(SocketFD);
return -1;
}
printf("going to listen!\n");
if(-1 == listen(SocketFD, 10))
{
perror("error listen failed");
close(SocketFD);
//exit(EXIT_FAILURE);
return -1;
}
ConnectFD = accept(SocketFD, NULL, NULL);
if(0 > ConnectFD)
{
perror("error accept failed");
close(SocketFD);
//exit(EXIT_FAILURE);
return -1;
}
addr.sin_family = AF_INET;
res = getsockname (ConnectFD, (struct sockaddr *)&addr, &addr_len);
// if you remove the following comment, that means, if you call
// two times of getsockname, the result will be correct.
//res = getsockname (ConnectFD, (struct sockaddr *)&addr, &addr_len);
printf("addr:%x\n", addr.sin_addr.s_addr);
while(1) {
if (getchar() == 'q')
break;
}
close(ConnectFD);
close(SocketFD);
return 0;
}
Below is client.c:
int main(void)
{
struct sockaddr_in stSockAddr;
int Res;
int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (-1 == SocketFD)
{
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&stSockAddr, 0, sizeof stSockAddr);
stSockAddr.sin_family = AF_INET;
stSockAddr.sin_port = htons(49335);
Res = inet_pton(AF_INET, "192.168.1.102", &stSockAddr.sin_addr);
if (0 > Res)
{
perror("error: first parameter is not a valid address family");
close(SocketFD);
exit(EXIT_FAILURE);
}
else if (0 == Res)
{
perror("char string (second parameter does not contain valid ipaddress");
close(SocketFD);
exit(EXIT_FAILURE);
}
if (-1 == connect(SocketFD, (struct sockaddr *)&stSockAddr, sizeof stSockAddr))
{
perror("connect failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
/* perform read write operations ... */
printf("client sockfd is successful\n");
while(1) {
if (getchar() == 'q')
break;
}
shutdown(SocketFD, SHUT_RDWR);
close(SocketFD);
return 0;
}
Use getsockname(2) on the socket returned from accept(2), not the socket returned from bind(2).
getsockname() gets name of passed socket.
in this example, you pass the socket which is created by
accept function in server.
this socket is in server side, so it's name & address is
related to server side.
if you want to know "who was connected to me"
you must use getpeername() instead of getsockname.
good luck
if you remove the following comment, that means, if you call
two times of getsockname, the result will be correct.
res = getsockname (ConnectFD, (struct sockaddr *)&addr, &addr_len);
you must init addr_len.
addr_len = sizeof(addr);
Related
I am currently coding a small chat application in C for learning network.
I develop using the Transmission Control Protocol with socket in C. I was able to connect to my server with a client not coded by myself (on local network). Now telnet succeed to connect to my chat server(so with server and telnet client on the same computer) and I can send and receive message BUT my very simple client cannot connect to it.
Since the begining I use port 9002 and right now I am trying to connect with IPv6 address ::1.
Here the "accept client" code of my server:
int main(void)
{
//Create the socket
int sock = socket(AF_INET6, SOCK_STREAM, 0);
printf("Socket créer\n");
//Set up the socket interface
struct sockaddr_in6 sin6 = { 0 };
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(PORT);
sin6.sin6_addr = in6addr_any;
//Bind the socket on the port
if(bind(sock, (struct sockaddr *) &sin6, sizeof(struct sockaddr_in6)) == SO_ERROR)
{
perror("bind()");
errx(EXIT_FAILURE, "Fail to bind");
}
//Make the sockey listen the port
if(listen(sock, MAX_CLIENT) == SO_ERROR)
{
perror("listen()");
errx(EXIT_FAILURE, "Fail to listen");
}
printf("Socket listening\n");
int csock;
size_t clientID = 0;
--snip--
while(1)
{
struct sockaddr_in6 csin6;
memset(&csin6, 0, sizeof(struct sockaddr_in6));
int sin6size = sizeof(struct sockaddr_in6);
//Accept a communication
printf("Wait for communication\n");
csock = accept(sock, (struct sockaddr *) &csin6, &sin6size);
printf("Connection accepted\n");
char msg[16];
sprintf(msg, "CONNECTED - %zu\n", clientID);
send(csock, msg, sizeof(msg), 0);
printf("Client %zu connected\n", clientID);
//Handle client
--snip--
}
So this is a basic connection with socket using connected communication. The server handle several client in the while loop thanks to threading.
Here the code of the client:
void *sender(void *arg)
{
int socket = (int)(long)arg;
char buffer[BUFF_SIZE];
while(1)
{
scanf("%s", buffer);
send(socket, buffer, strlen(buffer), 0);
bzero(buffer, BUFF_SIZE);
}
}
int main(int argc, char *argv[])
{
if(argc < 2)
errx(EXIT_FAILURE, "Usage: ./client <server ip>\n");
//Create the socket
int sock = socket(AF_INET6, SOCK_STREAM, 0);
struct hostent *hostinfo = NULL;
hostinfo = gethostbyname2(argv[1], AF_INET6);
if(hostinfo == NULL)
errx(EXIT_FAILURE, "Can't connect to the server\n");
//Set up the socket interface
struct sockaddr_in6 sin6 = { 0 };
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(PORT);
sin6.sin6_addr = *(struct in6_addr *)hostinfo->h_addr;
if(connect(sock, (struct sockaddr *) &sin6, sizeof(struct sockaddr)) == SO_ERROR)
{
perror("connect()");
errx(EXIT_FAILURE, "Fail to connect");
}
printf("Connection established\n");
pthread_t sending;
if(pthread_create(&sending, NULL, sender, (void *)(long)sock) != 0)
printf("Fail to create a thread\n");
//Handle reception
char buffer[BUFF_SIZE];
int n;
while((n = recv(sock, buffer, BUFF_SIZE - 1, 0)) >= 0)
{
buffer[n] = '\0';
printf("%s", buffer);
}
printf("Erreur: %d\nConnection broken\n", n);
pthread_cancel(sending);
close(sock);
return EXIT_SUCCESS;
}
So I start the client with:
~ ./client ::1
The output is the following:
Connection established
Error: -1
Connection broken
While the server is still "Waiting for communication". This means that the server do not accept the connection but the client succeed to connect.
Thank you for you help.
It is probably already the connect(), which fails here:
if(connect(sock, (struct sockaddr *) &sin6, sizeof(struct sockaddr)) == SO_ERROR)
SO_ERROR is not meant to be used here, but as a socket option when retrieving the error when an asynchronous connect fails. A (synchronous) connect() returns -1 on error and sets errno, so do
if(connect(sock, (struct sockaddr *) &sin6, sizeof(struct sockaddr)) == -1) {
...
Later, the recv here:
while((n = recv(sock, buffer, BUFF_SIZE - 1, 0)) >= 0)
fails with errno ENOTCONN, since the connection failed beforehand.
The same SO_ERROR mistake is present at various locations in your server code; it is possible, that already the bind() there fails! The call to listen() will then autobind it to a free ephemereal port, so the call as well as the call to accept() will succeed.
Why can the call to bind() fail? You might have to set the socket option SO_REUSEADDR when (re-)starting the server, otherwise it might refuse to use a recently bound port if connections are still in TIME_WAIT state. Place this directly before the bind() call:
int one = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
This might help.
I have a simple tcp client server program. Client sends text, server prints it ito terminal. I need to make it so client can connect to server by ip address, no just a port. Tried changing something in my localhost server, but it only broke it and it doesn't work anymore. What's whong in it?
Here's the server code:
int server(int port)
{
int fd;
struct ifreq ifr;
char * addres;
fd = socket(AF_INET, SOCK_STREAM, 0);
/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;
/* I want IP address attached to "eth0" */
strncpy(ifr.ifr_name, "em0", IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
addres=inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
//until this part, i'm getting my em0 address to a variable which I want to use later
//to specify on which address I want my server to be
int s, s2, t, len;
int z;
struct sockaddr_in local, remote;
char str[100];
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
local.sin_family = AF_INET;
local.sin_addr.s_addr = inet_addr(addres); //inet_addr(inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
printf("binder");
if (bind(s, (struct sockaddr *)&local, sizeof(local)) == -1) {
perror("bind");
exit(1);
}
if (listen(s, 5) == -1) {
perror("listen");
exit(1);
}
for(;;) {
int done, n;
printf("Waiting for a connection...\n");
t = sizeof(remote);
if ((s2 = accept(s, (struct sockaddr *) &remote, (socklen_t *) &t)) == -1) {
perror("accept");
exit(1);
}
printf("Connected...\n");
done = 0;
do {
n = recv(s2, str, 100, 0);
if (n <= 0) {
if (n < 0) perror("recv");
done = 1;
}
if (!done)
printf("%s", str);
fflush(stdout);
sleep(1);
} while (!done);
close(s2);
}
return 0;
}
It should start listening at given port, and on em0 interface address, but it seems to be doing nothing at all. In driver function I just pass the int representing port which I want to use.
Can I connect my client with that server using ip address?
My driver funtion chooses if I want to start a server or a client, it's all in one file.
To start a server i use:
./main.o -l [port]
and to start a client I'd want to use:
./main.o [address] [port]
Client seems to be working fine, just refuses to connect, only problem (as far as I'm aware) is a server. Maybe you'll catch what am I doing wrong, I'm sitting with it for couple of hours basically hopeless.
Trying to create a server-client application, and I'm having quite a bit of trouble setting up the connection on the server-side. After setting up the socket, and bind()ing the socket, my listen()-call fails with the error message
listen: Invalid argument
which I get from perror()-ing the case where listen() returns -1.
The synopsis of the program is the following: I use getaddrinfo() to generate a linked list of struct addrinfo's, loop through that until I find one that I can successfully create a socket with, then bind() and finally listen().
The listen() call goes as follows:
if ((status = listen(socket_fd, BACKLOG_SIZE)) == -1) {
perror("listen");
close(socket_fd);
freeaddrinfo(res);
exit(EXIT_FAILURE);
}
To be sure, I've printed the values of socket_fd and BACKLOG_SIZE, turning out to be 3 and 5, respectively. Have been debugging for hours now, and I simply cannot find out where the problem lies. Haven't found anyone with the same issue on stackOverflow, either...
Thank you in advance for any help!
Full program:
int main(int argc, char* argv[]) {
int port_no = server_usage(argc, argv);
ready_connection(port_no);
/* Synopsis:
getaddrinfo()
socket()
bind()
listen()
accept()
*/
int socket_fd = setup_socket(NULL, port_no);
struct sockaddr_storage their_addr;
socklen_t addr_size = sizeof(their_addr);
int new_fd = 0;
// Allow reuse of sockets
int activate=1;
setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &activate, sizeof(int));
if ((status = bind(socket_fd, res->ai_addr, res->ai_addrlen)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
if ((status = connect(socket_fd, res->ai_addr, res->ai_addrlen)) == -1) {
perror("connect");
close(socket_fd);
freeaddrinfo(res); // free the linked-list
exit(EXIT_FAILURE);
}
if ((status = listen(socket_fd, BACKLOG_SIZE)) == -1) {
perror("listen");
close(socket_fd);
freeaddrinfo(res); // free the linked-list
exit(EXIT_FAILURE);
}
if ((new_fd == accept(socket_fd, (struct sockaddr *)&their_addr, &addr_size)) == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
char buffer[BUFSIZE];
recv(new_fd, buffer, BUFSIZE, 0);
close(socket_fd);
close(new_fd);
freeaddrinfo(res); // free the linked-list
return 0;
}
setup_socket()-function:
int setup_socket(char* hostname, int port_no) {
// hints is mask struct, p is loop variable
struct addrinfo hints, *p;
memset(&hints, 0, sizeof hints); // make sure the struct is empty
// TODO IPv6-support?
hints.ai_family = AF_INET; // only IPv4 supported
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
char port_str[6]; // max port size is 5 digits + 0-byte
memset(port_str, 0, 6);
sprintf(port_str, "%d", port_no);
if ((status = getaddrinfo(hostname, port_str, &hints, &res)) == -1) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(EXIT_FAILURE);
}
int socket_fd = 0;
for (p = res; p != NULL; p = p->ai_next) {
if ((socket_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
}
if (socket_fd == 0) {
errno = ENOTSOCK;
perror("no socket");
exit(EXIT_FAILURE);
}
return socket_fd;
}
You cannot connect(), then listen() on the same socket. Lose the connect().
I have a TCP server that is listening on two different ports . I created two different sockets one on port 8888 and one on port 6634. I listen on those ports and then i add the two sockets in FD_SET and pass them to select() function ...
When a socket is ready to read i check with FD_ISSET to see on which port i have message to read .
any way when i connect to port 8888 the conception is successful and i can send towards the server and receive ... when i ctrl+c the client the select function is returning again 1 and now my accept() fails ...
when i do the same thing on port 6634 everything is ok... the code stops at the select() and waits for a socket to be ready to read!
can anyone tell me WHY is this happening ?
take a look at my code in attachment
int main()
{
SOCKET conn_request_skt; /* socket where connections are accepted */
char buf[RBUFLEN], buf1[RBUFLEN]; /* reception buffer */
uint16_t lport_n, lport_h, lport_n1, lport_h1; /* port where the server listens (net/host byte ord resp.) */
int bklog = 2; /* listen backlog */
SOCKET s,s1;
int result, n;
socklen_t addrlen;
struct sockaddr_in saddr, caddr; /* server and client address structures */
int optval,childpid,i; /* flag value for setsockopt */
int connectcnt; /* number of connection requests */
fd_set readfds;
/* Initialize socket API if needed */
SockStartup();
/* input server port number */
lport_h=6634;
lport_n = htons(lport_h);
lport_h1=8888;
lport_n1 = htons(lport_h1);
/* create the socket */
printf("Creating first socket\n");
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
err_fatal("socket() failed");
printf("done, socket number %u\n",s);
/* bind the socket to any local IP address */
saddr.sin_family = AF_INET;
saddr.sin_port = lport_n;
saddr.sin_addr.s_addr = INADDR_ANY;
showAddr("Binding to address first socket", &saddr);
result = bind(s, (struct sockaddr *) &saddr, sizeof(saddr));
if (result == -1)
err_fatal("bind() failed");
printf("done.\n");
printf("Creating second socket\n");
s1 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s1 == INVALID_SOCKET)
err_fatal("socket() failed");
printf("done, socket number %u\n",s1);
/* bind the socket to any local IP address */
saddr.sin_port=lport_n1;
showAddr("Binding to address second socket", &saddr);
result = bind(s1, (struct sockaddr *) &saddr, sizeof(saddr));
if (result == -1)
err_fatal("bind() failed");
printf("done.\n");
/* listen */
printf ("Listening at socket %d with backlog = %d \n",s,bklog);
result = listen(s, bklog);
if (result == -1)
err_fatal("listen() failed");
printf("done.\n");
printf ("Listening at socket %d with backlog = %d \n",s1,bklog);
result = listen(s1, bklog);
if (result == -1)
err_fatal("listen() failed");
printf("done.\n");
for (;;)
{
FD_ZERO(&readfds); /* initialize the fd set */
FD_SET(s, &readfds);
FD_SET(s1, &readfds); /* add socket fd */
printf("here \n");
printf("result bifore select is %d \n", result);
result=select(s1+1, &readfds, 0, 0, 0);
printf("result after select is %d \n", result);
if(result<0)
{
err_fatal("select() failed");
}
if(result>0)
{
if(FD_ISSET(s,&readfds))
{
conn_request_skt=s;
/* accept next connection */
addrlen = sizeof(struct sockaddr_in);
s = accept(conn_request_skt, (struct sockaddr *) &caddr, &addrlen);
if (s == INVALID_SOCKET)
err_fatal("accept() failed");
showAddr("Accepted connection from", &caddr);
printf("new socket: %u\n",s);
/* serve the client on socket s */
for (;;)
{
n=recv(s, buf, RBUFLEN-1, 0);
if (n < 0)
{
printf("Read error\n");
closesocket(s);
printf("Socket %d closed\n", s);
break;
}
else if (n==0)
{
printf("Connection closed by party on socket %d\n",s);
//closesocket(s);
break;
}
else
{
printf("Received line from socket %03d :\n", s);
buf[n]=0;
printf("[%s]\n",buf);
if(writen(s, buf, n) != n)
printf("Write error while replying\n");
else
printf("Reply sent\n");
}
}
}
if(FD_ISSET(s1,&readfds))
{
conn_request_skt=s1;
/* accept next connection */
addrlen = sizeof(struct sockaddr_in);
printf("bifore accept! \n");
s1 = accept(conn_request_skt, (struct sockaddr *) &caddr, &addrlen);
if (s1 == INVALID_SOCKET)
err_fatal("accept() failed");
showAddr("Accepted connection from", &caddr);
printf("new socket: %u\n",s1);
/* serve the client on socket s */
for (;;)
{
n=recv(s1, buf, RBUFLEN-1, 0);
if (n < 0)
{
printf("Read error\n");
closesocket(s1);
printf("Socket %d closed\n", s1);
break;
}
else if (n==0)
{
printf("Connection closed by party on socket %d\n",s1);
//closesocket(s);
break;
}
else
{
printf("Received line from socket %03d :\n", s1);
buf[n]=0;
printf("[%s]\n",buf);
if(writen(s1, buf, n) != n)
printf("Write error while replying\n");
else
printf("Reply sent\n");
}
}
}
}
}
}
The first listener socket is created with:
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
And then the data socket is accepted with:
conn_request_skt=s;
s = accept(conn_request_skt, (struct sockaddr *) &caddr, &addrlen);
See? The next loop, when you are going to select over the listener socket, s no longer holds that socket, but the (closed) data socket.
The solution is to use different variables for the listener socket and the data socket (conn_request_skt is just obfuscating the issue).
You are overwriting your socket variable s1 with the result of the accept() call. So s1 contains now the descriptor of the socket you are actually reading from. Then you close that socket. But in the next pass of the main loop, you check for readability on that (now closed) descriptor, which does not work.
I believe it would be better not to reuse variables in this case. Use a new variable for the actual connection socket, so that you retain the original listening socket in s1.
I am new to working with TCP sockets and I do not understand the errors I am getting when running my programs. I have two programs that when run simultaneous I would like to be able to pass messages between. The initial message gets through but then when trying to return another message I get two errors. When I run my first program the output is:
Input Message: hello
Waiting for incoming connections...
Connection accepted
Message Sent
Connection error: Transport endpoint is already connected
Now running the other program simultaneously gives:
Input Message: Hello Back
Connected
Message received
hello
Bind error: Cannot assign requested address
If anyone could explain these "cannot assign requested address" and " Transport endpoint is already connected" errors I would greatly appreciate it!! Thanks!
The first program is:
int main(int argc, char *argv[]) {
int socket_info, new_socket;
struct sockaddr_in server, client;
char message[100];
char incoming_message[100];
printf("Input Message: ");
fgets(message, 100, stdin);
//create socket
socket_info = socket(AF_INET, SOCK_STREAM, 0);
if (socket_info == -1) {
printf("Could not create socket");
}
//assign values
server.sin_addr.s_addr = INADDR_ANY;
server.sin_family = AF_INET;
server.sin_port = htons( 1100 );
int y=1;
if(setsockopt(socket_info, SOL_SOCKET, SO_REUSEADDR, (char*)&y, sizeof(y)) == -1) {
perror("set reuseaddr");
return -1;
}
//binds socket
if (bind(socket_info, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("Bind error");
return 1;
}
//listen
listen(socket_info , 5);
//waiting for connection
puts("Waiting for incoming connections...");
int c = sizeof(struct sockaddr_in);
//accept connection
new_socket = accept(socket_info, (struct sockaddr *)&client, (socklen_t*)&c);
if (new_socket < 0){
perror("accept failed");
return 1;
}
puts("Connection accepted");
//send message
if( send(new_socket , message , strlen(message) , 0) < 0) {
perror("Send failed");
return 1;
}
puts("Message Sent");
//connects
if (connect(socket_info, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("Connection error");
return 1;
}
puts("Connected");
//Receive an incoming message
if( recv(socket_info, incoming_message , sizeof(incoming_message) , 0) < 0) {
perror("Received failed");
return 1;
}
puts("Message received");
incoming_message[strlen(incoming_message)-1]=0;
puts(incoming_message);
close(socket_info);
}
The second program is:
int main(int argc, char *argv[]) {
int socket_info, new_socket;
struct sockaddr_in server, client;
char incoming_message[100];
char message[100];
printf("Input Message: ");
fgets(message, 100, stdin);
//create socket
socket_info = socket(AF_INET, SOCK_STREAM, 0);
if (socket_info == -1) {
printf("Could not create socket");
}
//assign values
server.sin_addr.s_addr = inet_addr("172.21.8.178");
server.sin_family = AF_INET;
server.sin_port = htons( 1100 );
//connects
if (connect(socket_info, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("Connection error");
return 1;
}
puts("Connected");
//Receive an incoming message
if( recv(socket_info, incoming_message , sizeof(incoming_message) , 0) < 0) {
perror("Received failed");
return 1;
}
puts("Message received");
incoming_message[strlen(incoming_message)-1]=0;
puts(incoming_message);
int y=1;
if(setsockopt(socket_info, SOL_SOCKET, SO_REUSEADDR, (char*)&y, sizeof(y)) == -1) {
perror("set reuseaddr");
return -1;
}
//binds socket
if (bind(socket_info, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("Bind error");
return 1;
}
//listen
listen(socket_info , 5);
//waiting for connection
puts("Waiting for incoming connections...");
int c = sizeof(struct sockaddr_in);
//accept connection
new_socket = accept(socket_info, (struct sockaddr *)&client, (socklen_t*)&c);
if (new_socket < 0){
perror("accept failed");
return 1;
}
puts("Connection accepted");
//send message
if( send(new_socket , message , strlen(message) , 0) < 0) {
perror("Send failed");
return 1;
}
puts("Message Sent");
close(socket_info);
}
if (connect(socket_info, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("Connection error");
return 1;
}
Connection error: Transport endpoint is already connected
I asssume socket_info above should be new_socket?
You can't connect a listening socket.
You don't need to connect the listening socket. You have just accepted a socket from a client connection. You should do your I/O to that client with that socket.
In your second program:
if(setsockopt(socket_info, SOL_SOCKET, SO_REUSEADDR, (char*)&y, sizeof(y)) == -1) {
perror("set reuseaddr");
return -1;
}
This is futile. The socket is already bound, implicitly, via the connect() call preceding.
//binds socket
if (bind(socket_info, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("Bind error");
return 1;
}
Bind error: Cannot assign requested address
You can't bind a socket that is already connected.
Nor can you bind a socket to a remote address.
Nor can you listen on a connected socket.
Nor can you accept from it. You don't need to bind, or listen, or accept from it. You are already connected to the peer.
In short your code doesn't make any sense whatsoever. You need to find a proper tutorial and study it.
incoming_message[strlen(incoming_message)-1] = 0;
This makes even less sense. Here you are searching for a trailing null byte (which may not even be there) and replacing the byte before it by ... a null byte. Why?