TCP Client-Server "bad address" error (in C) - c

Although it seems to be correctly implemented, it keeps on returning me ERROR when I establish a connection using the loopback address(127.0.0.1).
In addition to a simple TCP Client/Server connection, I have added an additional case:
If the client tries to send data but finds the connection closed, it is closed too. I perform it by checking if received data is equal to 0 (recv).
Given error:
CLIENT:
Welcome to the Client mode
Please, enter the Server's IP Address and Port (eg. 192.128.192.0 1320)
127.0.0.1 2700
Connected to the server. Now you can send messages
Please, enter a message. Enter "FINISH" if you want to finish the connection
ECHO
client: connection closed ->: Success
(1 bytes)Closing the connection
SERVER:
Hello and welcome to the Server mode
Please, enter the Server's Port (eg. 1320)
2700
Server socket successfully configured
Server listening [Clients allowed: 5]
server: accept error: Bad address
Client implementation:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
/**
struct sockaddr{
uint8_t sa_len; // struct length
sa_family_t sa_family; //protocol family: AF_XXX
char sa_data[8]; //socket addr
}
*/
//void notConnected();
int main(){
struct sockaddr_in serv_addr; //port + ip_addr
int my_socket, tcp_port;
char serv_host_addr[30];
char buffer[1024], inbuff[1024];
int io_buffer;
printf("Welcome to the Client mode\n");
//CONFIGURING THE CONNECTION
my_socket = socket(AF_INET, SOCK_STREAM, 0);//(2)
if(my_socket < 0){
perror("client: socket() error ->");
exit(EXIT_FAILURE);
}
bzero(&serv_addr, sizeof(serv_addr));//(4)
printf("Please, enter the Server's IP Address and Port (eg. 192.128.192.0 1320) \n");
scanf("%s %d", serv_host_addr, &tcp_port);//(1)
serv_addr.sin_family = AF_INET ;
serv_addr.sin_port = htons(tcp_port);
if(inet_pton(AF_INET,serv_host_addr,&serv_addr.sin_addr) < 1){
perror("client: inet_pton() error ->");
exit(EXIT_FAILURE);
}
if((connect(my_socket, (struct sockaddr *) &serv_addr, sizeof(serv_addr) )) < 0)//(5)
{
perror("client: connect() error ->");
exit(EXIT_FAILURE);
}
//ONCE CONNECTED, START THE SENDING/RECEIVING
printf("Connected to the server. Now you can send messages\n");
bzero(&buffer, sizeof(buffer));
while(strcmp(buffer, "OK\n") != 0){
printf("Please, enter a message. Enter \"FINISH\" if you want to finish the connection\n");//(3)
bzero(&buffer, sizeof(buffer));
fgets(buffer, sizeof(buffer), stdin);
io_buffer = send(my_socket, buffer, strlen(buffer),0);//(6)
if(io_buffer < 0){
perror("client: send() error ->");
exit(EXIT_FAILURE);
}
printf("ECHO %s (%d bytes)", buffer, io_buffer);
//RECEIVE AND CHECK IF CONNECTION HAS BEEN CLOSED
io_buffer = recv(my_socket, buffer, sizeof(buffer),0);
if(io_buffer < 0){
perror("client: recv() error ->");
exit(EXIT_FAILURE);
}
else if(io_buffer == 0){ //THIS IS SERVER IS CLOSED
perror("client: connection closed ->");
break;
}
printf("ECHO %s (%d bytes)", buffer, io_buffer);
}
printf("Closing the connection \n");
for(int i=0; i < 5; i++){
printf(". ");
usleep(500000);
}
close(my_socket);
}
Server implementation:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define LISTENQ 5
int main()
{
struct sockaddr_in cli_addr, serv_addr;
char buffer[1024];
int serv_socket, cli_socket, clilen, io_buffer;
int tcp_port;
printf("Hello and welcome to the Server mode\n");
// ASKING FOR PORT NUMBER
if((serv_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("server: can't open stream socket");
exit(EXIT_FAILURE);
}
printf("Please, enter the Server's Port (eg. 1320) \n");
scanf("%d", &tcp_port);
// CONFIGURING THE CONNECTION
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(tcp_port);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// ASSIGNING A NAME TO THE SOCKET
if(bind(serv_socket,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){
perror("server: can't assign a name to the socket");
exit(EXIT_FAILURE);
}
printf("Server socket successfully configured\n");
printf("Server listening [Clients allowed: %d]\n", LISTENQ);
if(listen(serv_socket, LISTENQ) < 0)
{
perror("server: fail to listen network");
exit(EXIT_FAILURE);
}
// READ & WRITE STREAM
while(1){
//returns a file descriptor for the client
cli_socket = accept(serv_socket,(struct sockaddr *) &cli_addr,(socklen_t *) sizeof(cli_addr));
if(cli_socket < 0){
perror("server: accept error");
exit(EXIT_FAILURE);
}
printf("Server successfully connected to Client\n");
while(1)
{
if ((io_buffer=recv(cli_socket,buffer,sizeof(buffer),0))<0){
perror("ERROR: recv");
exit(EXIT_FAILURE);
}
printf("\"%s\" received from client", buffer);
if(strcmp(buffer, "FINISH") == 0)
{
break;
}
if ((io_buffer=send(cli_socket,buffer,strlen(buffer),0))!=strlen(buffer)){
perror("ERROR: send");
exit(EXIT_FAILURE);
}
bzero(buffer, sizeof(buffer));
}
strcpy(buffer, "OK");
if ((io_buffer=send(cli_socket, buffer, strlen(buffer), 0)) != strlen(buffer)){
perror("ERROR: send");
exit(EXIT_FAILURE);
}
printf("\"OK\" message sent to the Client.\n");
printf("Closing the connection \n");
for(int i=0; i < 5; i++)
{
printf(". ");
usleep(500000);
}
close(cli_socket);
}
}

In your original question, your accept call looks like this:
cli_socket = accept(serv_socket,(struct sockaddr *) &cli_addr,
(socklen_t *) sizeof(cli_addr));
This passes "(socklen_t *) sizeof(cli_addr)" as the third parameter to accept. This is expected to be a pointer to the size of the structure. You should be passing in a pointer to a socklen_t containing the size of the structure passed as parameter two. The size you're currently passing in is being interpreted as an address, which is then causing your program to crash when it is referenced. The code should look like this:
socklen_t cli_addr_size = sizeof(cli_addr);
cli_socket = accept(serv_socket,(struct sockaddr *) &cli_addr,
&cli_addr_size);

Related

Client stuck when trying to connect via TCP/IP

I am new with socket programming and I have been following this tutorial: https://www.geeksforgeeks.org/tcp-server-client-implementation-in-c/
But it is only to use it in the local machine and my goal is to connect an embedded system with my computer (the computer is the server and the embedded system is the client).
To achieve the connection between the two systems, I have changed the servaddr.sin_addr.s_addr part of the client.c code, introducing the IP of the server in that line.
My server code (it gets compiled via gcc in the computer):
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function designed for chat between client and server.
void func(int connfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(connfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// and send that buffer to client
write(connfd, buff, sizeof(buff));
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server accept failed...\n");
exit(0);
}
else
printf("server accept the client...\n");
// Function for chatting between client and server
func(connfd);
// After chatting close the socket
close(sockfd);
}
My client code (it gets compiled via gcc in the embedded system)
#include <arpa/inet.h> // inet_addr()
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> // bzero()
#include <sys/socket.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) {
printf("Client Exit...\n");
break;
}
}
}
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("192.168.182.128");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr))
!= 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// function for chat
func(sockfd);
// close the socket
close(sockfd);
}
The issue comes when I execute the client executable in the embedded system (after executing the server executable in the computer), as it gets stuck when trying to connect:
root#imx8mq-var-dart:~# ./client
Socket successfully created..
(infinitely here)
What am I doing wrong? Am I missing something?

Is it possible to launch multiple servers listening to a different IP socket address?

I'm trying to launch multiple servers, at once, in a c program. For the sake of simplicity let's say 5 servers.
If I understand well the sockets, each of them must be listening to a different IP socket address (different PORT, different IP interface address).
I thought to do that inside a loop, incrementing port number by i at each turn. Here's my current code just to launch one server. I know it's possible with bash by launching the same process in background, but in C I really don't know how to do that and if it's even possible
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <errno.h>
long PORT;
int main(int argc, char const *argv[])
{
/* 1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send
*/
int listenerSocket; /* socket for accepting connections */
int clientSocket; /* socket connected to client */
struct sockaddr_in server;
struct sockaddr_in client; /* client address information */
char buf[100]; /* buffer for sending & receiving data */
int errnum;
listenerSocket = socket(AF_INET, SOCK_STREAM, 0);
if(listenerSocket == -1){
perror("erreur lors de la création du socket");
}
PORT = strtol(argv[1], NULL, 10);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port= htons(PORT);
if (bind(listenerSocket, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
puts("Server waiting for connection...");
while(1){
if (listen(listenerSocket, 5) < 0){
perror("listen failed");
exit(EXIT_FAILURE);
}
int c = sizeof(client);
if((clientSocket = accept(listenerSocket, (struct sockaddr*) &client, &c)) < 0){
puts("error accepting the request");
perror("Accept()");
}
puts("connection accepted");
while(1){
if( recv(clientSocket, buf, sizeof(buf), 0) < 0) {
errnum = errno;
perror("Recv()");
printf("val printed by errno: %d\n",errno);
}
printf("Message : %s\n", buf);
}
if (send(clientSocket, buf, sizeof(buf), 0) < 0)
{
perror("Send()");
exit(7);
}
close(clientSocket);
close(listenerSocket);
printf("Server ended successfully\n");
exit(0);
}

Linux C socket - keep server alive

I'm using C to implement a simple client-server retrieval system with Linux socket. I've now successfully connect the remote server, but when I close the connection, the server went down, i.e. the server program stopped.
What should I do avoid this?
here's sample of my code:
server:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
int main(void)
{
int optval;
socklen_t optlen = sizeof(optval);
char str[100] = "";
int listen_fd, conn_fd;
struct sockaddr_in servaddr;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
// check if on
getsockopt(listen_fd, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen);
printf("keep alive is %s\n", (optval? "ON" : "OFF"));
// set it on
optval = 1;
optlen = sizeof(optval);
setsockopt(listen_fd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen);
printf("done, check again.\n");
printf("keep alive is %s\n", (optval? "ON" : "OFF"));
bzero( &servaddr, sizeof(servaddr));
// set appropriate protocol and port number (15792)
// the htons() function converts the unsigned short integer
// from host byte order to network byte order.
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
servaddr.sin_port = htons(15792);
// Bind a name to a socket
bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
// listening for incoming connection
listen(listen_fd, 10);
// accept a connection on a socket
conn_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
do
{
// set str to null
bzero(str, 100);
// Read from a file descriptor (linux all)
read(conn_fd,str,100);
// print the received message
// printf("Received: %s\n",str);
if (!strcmp(str, "GET TIME\n"))
{
bzero(str, 100);
time_t clocks;
clocks = time(NULL);
sprintf(str, "%s", ctime(&clocks));
write(conn_fd, str, strlen(str));
//close(conn_fd);
}
else
{
bzero(str, 100);
strcpy(str, "ERROR: No such command.\n");
write(conn_fd, str, strlen(str));
//close(conn_fd);
}
} while (1);
}
client:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
// declare necessary variables
int sockfd;
char recv[1024] = "";
char command[100] = "";
struct sockaddr_in servaddr;
if (argc != 2)
{
printf("usage: %s <ip address>\n", argv[0]);
exit(EXIT_FAILURE);
}
// create a socket with the appropriate protocol
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("ERROR: Failed create cosket.\n");
exit(EXIT_FAILURE);
}
// Set all the socket structures with null values.
bzero(&servaddr, sizeof servaddr);
// set appropriate protocol and port number (1999)
// The htons() function converts the unsigned short integer
// hostshort from host byte order to network byte order.
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(15792);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, argv[1], &(servaddr.sin_addr)) <= 0)
{
printf("ERROR: Wrong ip address.\n");
exit(EXIT_FAILURE);
}
// attempt to connect to a socket
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
printf("ERROR: Failed at connect.\n");
exit(EXIT_FAILURE);
}
else
{
printf("------ connect successfull ------\n");
}
do
{
printf("> ");
fgets(command, 100, stdin);
write(sockfd, command, strlen(command));
if (!strcmp(command, "QUIT\n"))
{
close(sockfd);
break;
}
// print the receive stuff
read(sockfd, recv, sizeof(recv));
fputs(recv, stdout);
bzero(recv, 1024);
} while (1);
}
In your server code, the accept() function must be called in the do-while loop:
// listening for incoming connection
listen(listen_fd, 10);
do
{
// accept a connection on a socket
conn_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
...
close(conn_fd);
} while(1);
my question here is, why server ended if I close the connection from
the client.
Because then the blocking read call will return the value 0 indicating the connection was closed, which you promptly ignore. You then try (and fail) to compare the received data (which you have none) to the string and you will attempt to write the error message to the (now disconnected) client which will raise the SIGPIPE error which terminates your application.
– Some programmer dude

server recieving some junk value from the client?

#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <winsock.h>
#pragma once
#pragma comment (lib, "ws2_32.lib")
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <winsock.h>
#include <io.h>
SOCKET sock;
SOCKET fd;
char recv_data[10];
int port = 18001;
void CreateSocket()
{
struct sockaddr_in server, client; // creating a socket address structure: structure contains ip address and port number
printf("Initializing Winsock\n");
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD (1, 1);
if (WSAStartup (wVersionRequested, &wsaData) != 0){
printf("Winsock initialised failed \n");
} else {
printf("Initialised\n");
}
// create socket
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
// create socket address of the server
memset( &server, 0, sizeof(server));
// IPv4 - connection
server.sin_family = AF_INET;
// accept connections from any ip adress
server.sin_addr.s_addr = htonl(INADDR_ANY);
// set port
server.sin_port = htons(port);
//Binding between the socket and ip address
if(bind (sock, (struct sockaddr *) &server, sizeof(server)) < 0)
{
printf("Bind failed with error code: %d", WSAGetLastError());
}
//Listen to incoming connections
if(listen(sock,3) == -1){
printf("Listen failed with error code: %d", WSAGetLastError());
}
printf("Server has been successfully set up - Waiting for incoming connections");
int len;
len = sizeof(client);
fd = accept(sock, (struct sockaddr*) &client, &len);
if (fd < 0){
printf("Accept failed");
}
//echo(fd);
printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
//closesocket(fd);
}
int main()
{
CreateSocket();
while(1)
{
if(fd == -1)
{
printf("socket error\n");
}
else
{
recv(fd, recv_data, 9, 0);
printf("value is %s", recv_data);
}
}
return 0;
}
The above is a server code : I am creating a socket and accepting the data from the client. The client is sending a data and the server is accepting it.
If the client sends a to the server then the server will add some junk characters to it. If the client sends 4 characters then it will receive all the four characters. if the client sends one or two characters :Why the server is receiving some junk value ??
This is because, recv does not append NULL character at the end of the string. You have to explicitly add the NULL character. So, use return value of recv call and use it to append the NULL character.
int retval;
retval = recv(fd, recv_data, 9, 0);
if(retval != SOCKET_ERROR) {
recv_data[retval] = '\0';
printf("value is %s", recv_data);
}
'\0' is the only character which will differ you from char array and string.
Since you are using %s to print the string it is necessary to add the '\0' character at the end.

Client socket won't open using socket() function in a chat client

So this is a work in progress right now, but when I run the commands:
./server 4444
and from a different terminal window, ./client localhost 4444
The client stops at the "Error opening socket."
I have no idea why, and any advice will be greatly appreciated. I am fully aware this code is buggy and incomplete, but I cannot move forward without first getting my client and server to connect properly.
Here is my code:
client.c
#include "../lib/sockettalk.h"
#include "../lib/my.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
//#define MAX_SIZE=255
int main(int argc, char **argv)
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);//only need one socket since you are the only one connecting
int n;
char buffer[MAX_SIZE];
struct sockaddr_in serv_addr;
struct hostent *server;
int portnum = atoi(argv[2]);
if(argc < 3)
{
printf("Check your arguments.");
exit(0);
}
//printf("%d", portnum);
if(portnum < 2000 || portnum > 65535)//must be greater than 5000 to avoid conflictin ports
{
printf("Error, port number is out of bounds. Must be >2000 AND <65535.");
printf("Please enter a valid port number next time.");
exit(0);
}
if(sockfd < 0);
printf("Error opening socket. \n");
else
printf("Opened socket directly. \n");
if((server = gethostbyname(argv[1])) == 0)
{
printf("Error, no host. \n");
exit(0);
}
//memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htonl(portnum);
if((connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) < 0)
{
printf("Error connecting. \n");
}
while(1)
{
//clear and write a message
memset(buffer, '0', sizeof(buffer));
if((n = write(sockfd, buffer, my_strlen(buffer))) < 0)
{
printf("Error writing to server. \n");
exit(1);
}
printf("Client: ");
printf("%s", buffer);
printf(" \n");
//clear and read
memset(buffer, '0', sizeof(buffer));
if((n = read(sockfd, buffer, MAX_SIZE)) < 0)
{
printf("Error reading from server. \n");
exit(1);
}
printf("Server: ");
printf("%s", buffer);
printf(" \n");
}
return 0;
}
server.c
#include "../lib/my.h"
#include "../lib/sockettalk.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int port = atoi(argv[1]);
int pid;
int n; //to read and write
char buffer[MAX_BUFFER_SIZE];
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
int newsockfd;
int clilen; //to be used in accept step as a dummy, need size of bytes
struct sockaddr_in cli_addr, serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
if (sockfd<0)
printf("Problem openning socket.\n");
else
{
printf("Openned socket successfully.\n");
}
serv_addr.sin_family = AF_INET; //address family
serv_addr.sin_port = port; //IP port
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); //IP address, INADDR_ANY allows program to work without knowing the IP address of machine it is running on.
if(bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)//assigns a name to a socket. we must also cast serv_addr to a pointer to a struct socketDDR
{
printf("Error binding socket. \n");
exit(1);
}
else
{
printf("Bound socket successfully. \n");
}
if(listen(sockfd, 5) < 0) //should be an already bound socket. 5 is the number of clients that can connect at once
{
printf("Error listning.\n");
exit(1);
}
while(1) //place into loop so that process can repeat for every new connection
{
//now a newsockfd needs to be created so that it gives every new client a unique identifir
newsockfd = accept(sockfd,(struct sockaddr*) &cli_addr, &clilen);
if(newsockfd < 0)
{
printf("Error accepting\n");
exit(1);
}
else
{
printf("Client is connected.\n");
}
if ((pid = fork()) < 0) //problem
{
printf("Error forking. \n");
exit(1);
}
else if(pid == 0) //forking is sucessful, is a child
{
close(sockfd); //closes from the child side
while(1)
{
memset(buffer, 0, sizeof(buffer));
n = read(newsockfd, buffer, MAX_BUFFER_SIZE);
if (n < 0)
{
printf("Error reading from client.\n");
exit(1);
}
printf("%s", buffer);
printf("\n");
memset(buffer, 0, sizeof(buffer));
fgets(buffer, 254, stdin);
n = write(newsockfd, buffer, strlen(buffer));
if(n < 0)
{
printf("Error writing to client.\n");
exit(1);
}
printf("Server: ");
printf("%s", buffer);
printf("\n");
}
close(sockfd);
}
}
return 0;
}
In the client, you aren't actually using the result of server = gethostbyname(...) anywhere. Indeed, you're leaving serv_addr.sin_addr uninitialized, so you're trying to connect to some random IP address (probably 0.0.0.0), which is of course failing.

Resources