C Client Server doesn't work as expected - c

I have this simple client-server written in C below. The client sends 2 numbers to the server and the server sends back to the client the sum of the 2 numbers. My problem is with sending back the sum from server to the client, I can't see why it does not work. it doesn't give any error, just the receivedData variable is not filled with the desired int. The client successfully sends the packet with the 2 numbers to the server and the server successfully receives them.
Please note that this is just a didactic example, and I didn't use threads for handling clients. It's just one client and one server.
Here is the server:
// SERVER
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#define PORT 2012
struct Packet
{
int a;
int b;
};
int main()
{
struct sockaddr_in clientAddress;
int sd;
if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("Error creating socketsss\n");
}
memset(&clientAddress, 0, sizeof(clientAddress));
clientAddress.sin_family = AF_INET;
clientAddress.sin_port = htons(PORT);
clientAddress.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sd, (struct sockaddr*)&clientAddress, sizeof(clientAddress)) < 0)
{
printf("Bind error\n");
}
if(listen(sd, 5) < 0)
{
printf("Listen error\n");
}
unsigned int len = 0;
int fd = accept(sd, (struct sockaddr*)&clientAddress, &len);
struct Packet received;
if(recv(fd, &received, sizeof(struct Packet), 0) < 0)
{
printf("Receive error");
}
int sum = received.a + received.b;
printf("Numarul ce trebui trimis este %d\n", sum);
if(send(sd, &sum, sizeof(sum), 0) < 0)
{
printf("Error sending data\n");
}
return 0;
}
And here is the client:
// CLIENT
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SERVER_IP "127.0.0.1"
#define PORT 2012
struct Packet
{
int a;
int b;
};
int main()
{
struct sockaddr_in serverAddress;
int sd;
if((sd = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("Error creating socket\n");
}
memset((char *)&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(SERVER_IP);
serverAddress.sin_port = htons(PORT);
if ((connect(sd,(struct sockaddr *)&serverAddress, sizeof(serverAddress))) < 0)
{
printf("Error connectiong to server!\n");
}
struct Packet packToSend;
packToSend.a = 14;
packToSend.b = 21;
if(send(sd, &packToSend, sizeof(packToSend), 0) < 0)
{
printf("Error sending data\n");
}
int receivedData = 0;
if(recv(sd, &receivedData, sizeof(int), 0) < 0)
{
printf("Receive error\n");
}
printf("I received %d \n", receivedData);
return 0;
}
Thanks!

You are sending on the listening socket, not the one you accepted.

Related

C Socket TCP, send array to server and response back to client in loop

I'm very new to socket and TCP, I'm trying to send an array of Int to the server, do some sorting and calculating, then send back the result to the client and repeat.
I tried a few different ways, I either got the result after I close the client or got into a infinite loop.
What is the proper way to keep reading from the client until the client hit EOF?
Here is my server code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char const *argv[]) {
struct sockaddr_in server, client;
int sock, csock, readSize, addressSize;
char buf[256];
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5999);
sock = socket(PF_INET, SOCK_STREAM, 0);
bind(sock, (struct sockaddr*)&server, sizeof(server));
listen(sock, 5);
addressSize = sizeof(client);
csock = accept(sock, (struct sockaddr *)&client, &addressSize);
int values[5];
while (read(csock, values, sizeof(values))) {
// Some sorting and calculating here
for (int i = 0; i < 5; i++) {
printf("%d ", values[i]);
}
}
close(sock);
return 0;
}
And here is my client code.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char const *argv[]) {
struct sockaddr_in server;
char buf[256];
int sock;
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5999);
sock = socket(PF_INET, SOCK_STREAM, 0);
connect(sock, (struct sockaddr *)&server, sizeof(server));
while (1) {
int values[5] = {0};
for (int i = 0; i < 5; i++)
scanf("%d", &values[i]);
write(sock, values, sizeof(values));
}
return 0;
}
Thanks for your help!
On Linux, I observed that if client is terminated with Ctrl-C, then server exits when read() returns 0 to signify EOF. If client is given a Ctrl-D, the stream's error state is set and this and all future scanf calls fail without setting values. This means values retain their zero initialization, which is sent to server in each iteration of the infinite loop.
Per #user207421, recv() which I guess how read() is implemented may return on error on windows to signify and errors. In this case, server would loop with the original code.
In either case, I added error checking for most of calsl (you should also add it for inet_addr()), and the server will terminate if read() returns either -1 or 0:
server:
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <unistd.h>
int main(int argc, char const *argv[]) {
struct sockaddr_in server, client;
int sock, csock;
socklen_t addressSize;
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5999);
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) {
printf("socket: %s\n", strerror(errno));
return 1;
}
if(bind(sock, (struct sockaddr*)&server, sizeof(server)) == -1) {
printf("bind: %s\n", strerror(errno));
return 1;
}
if(listen(sock, 5) == -1) {
printf("listen: %s\n", strerror(errno));
return 1;
}
addressSize = sizeof(client);
csock = accept(sock, (struct sockaddr *)&client, &addressSize);
if(csock == -1) {
printf("listen: %s\n", strerror(errno));
return 1;
}
int values[5];
ssize_t n;
while ((n = read(csock, values, sizeof(values)))) {
printf("read %zd\n", n);
if(n <= 0) break;
for (int i = 0; i < n / sizeof(*values); i++) {
printf("%d ", values[i]);
}
printf("\n");
}
close(sock);
return 0;
}
and client:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
int main(int argc, char const *argv[]) {
struct sockaddr_in server;
char buf[256];
int sock;
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5999);
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) {
printf("socket: %s\n", strerror(errno));
return 1;
}
if(connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1) {
printf("connect: %s\n", strerror(errno));
return 1;
}
while (1) {
int values[5] = {0};
for (int i = 0; i < 5; i++) {
int r = scanf("%d", &values[i]);
if(r == EOF) {
return 0;
}
}
ssize_t n = write(sock, values, sizeof(values));
if(n == -1) {
printf("write: %s\n", strerror(errno));
return 1;
}
printf("wrote %zd\n", n);
}
return 0;
}
and here is the output from the server:
$ ./server
read 20 bytes
1 2 3 4 5
and the client (note; client doesn't send partial data):
$ ./client
1
2
3
4
5
wrote 20
1

Why a TCP socket server written in C should not close client file descriptors in worker pthreads, but can close them in forked worker processes?

I wrote a simple TCP socket server in C, which creates a new child worker thread when it accepts a new connection request from a client and simply counts and sends numbers. If a client terminates, the corresponding child worker thread should also terminate, while the other threads should not.
If all clients are written in Python, when a client terminates, "Connection is reset by peer" is printed on the server, but everything else is fine, that is, other threads and clients are still working.
But if a client is written in C, when any clients and their corresponding child worker threads terminate, other threads also terminate, which is not expected. Why does it happen? I rewrote the server in Python, but this did not happen no matter what language the client is written in.
I then commented out close(*client_fd); and the issue is solved. I haven't got a clue, since it works fine in the server using fork().
The C code for server using pthread is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT 9000
#define CONNECTIONS 2
#define MAX_BUFFER_SIZE 1024
struct sockaddr_in socket_address;
socklen_t socket_address_size = sizeof(socket_address);
int server_fd;
void *handle_request(void *fd) {
int *client_fd = (int *) fd;
char buffer[MAX_BUFFER_SIZE] = {0};
for (int i = INT_MAX; send(*client_fd, buffer, strlen(buffer), 0) >= 0 && i >= 0; i--) {
printf("%d\r\n", i);
sprintf(buffer, "%d", i);
}
if (close(*client_fd) < 0) {
perror("close client_fd");
}
return NULL;
}
int main(int argc, char *argv[]) {
int option = 1;
char buffer[MAX_BUFFER_SIZE] = {0};
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &option, sizeof(option))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
socket_address.sin_family = AF_INET;
socket_address.sin_addr.s_addr = htonl(INADDR_ANY);
socket_address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *) &socket_address, socket_address_size) < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
if (listen(server_fd, CONNECTIONS) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
pthread_t threads[CONNECTIONS];
int client_fds[CONNECTIONS];
for (int i = 0; i < CONNECTIONS; i++) {
client_fds[i] = accept(server_fd, (struct sockaddr *) &socket_address, &socket_address_size);
if (client_fds[i] < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
if (pthread_create(&threads[i], NULL, handle_request, &client_fds[i]) < 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < CONNECTIONS; i++) {
if (pthread_join(threads[i], NULL) < 0) {
perror("pthread_join");
}
}
close(server_fd);
return EXIT_SUCCESS;
}
The C code for server using fork() is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#define PORT 9000
#define CONNECTIONS 2
#define MAX_BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
struct sockaddr_in socket_address;
socklen_t socket_address_size = sizeof(socket_address);
int server_fd, client_fd, option = 1;
char buffer[MAX_BUFFER_SIZE] = {0};
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &option, sizeof(option))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
socket_address.sin_family = AF_INET;
socket_address.sin_addr.s_addr = htonl(INADDR_ANY);
socket_address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *) &socket_address, socket_address_size) < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
if (listen(server_fd, CONNECTIONS) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
pid_t pids[CONNECTIONS];
for (int i = 0; i < CONNECTIONS; i++) {
pids[i] = fork();
if (pids[i] < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pids[i] == 0) {
if ((client_fd = accept(server_fd, (struct sockaddr *) &socket_address, &socket_address_size)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
for (int i = INT_MAX; send(client_fd, buffer, strlen(buffer), 0) >= 0 && i >= 0; i--) {
printf("%d\r\n", i);
sprintf(buffer, "%d", i);
}
close(client_fd);
return EXIT_SUCCESS;
}
}
for (int i = 0; i < CONNECTIONS; i++) {
int wstatus;
if (waitpid(0, &wstatus, WUNTRACED) < 0) {
perror("waitpid");
}
}
close(server_fd);
return EXIT_SUCCESS;
}
The C code for client is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define IP_ADDRESS "127.0.0.1"
#define PORT 9000
#define MAX_BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int socket_fd;
struct sockaddr_in socket_address;
socklen_t socket_address_size = sizeof(socket_address);
ssize_t message_len;
char buffer[MAX_BUFFER_SIZE] = {0};
if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket");
exit(EXIT_FAILURE);
}
socket_address.sin_family = AF_INET;
socket_address.sin_addr.s_addr = inet_addr(IP_ADDRESS);
socket_address.sin_port = htons(PORT);
if (connect(socket_fd, (struct sockaddr *) &socket_address, socket_address_size) < 0) {
perror("connect");
exit(EXIT_FAILURE);
}
while ((message_len = recv(socket_fd, buffer, MAX_BUFFER_SIZE, 0)) > 0) {
buffer[message_len] = '\0';
puts(buffer);
}
close(socket_fd);
return EXIT_SUCCESS;
}
The Python code for server is as follows:
import socket
import threading
HOST = ''
PORT = 9000
CONNECTIONS = 2
TRUNK_SIZE = 1024
def handle_request(connection):
with connection:
count = 0
while True:
state = connection.send(f'{count}\r\n'.encode('utf-8'))
if not state:
print(f"Connection closed from {address}.")
break
print(count)
count += 1
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR | socket.SO_REUSEPORT, 1)
s.bind((HOST, PORT))
s.listen(CONNECTIONS)
threads = []
for c in range(CONNECTIONS):
connection, address = s.accept()
print(f'Connected by {address}.')
thread = threading.Thread(target=handle_request, args=(connection,), daemon=True)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
The Python code for client is as follows:
import socket
HOST = '127.0.0.1'
PORT = 9000
TRUNK_SIZE = 1024
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
data = s.recv(TRUNK_SIZE).decode('utf-8')
if not data:
print("Connection closed.")
break
print(data)
If your whole process suddenly goes down while writing to a socket, then due to a SIGPIPE signal you received (indicated by the error EPIPE). The standard action of SIGPIPE is to terminate the process. Implement a signal handler which will catch SIGPIPE signals (and probably ignore or deal with it).
The message "Connection is reset by peer" is an indication of a caught SIGPIPE signal.

C Program Attempting to send data, from serveride to client via tcp causing immediate crash

As the title stated - any atempts made by the serverside to send data back to the client result in an imediate crash (segmentation fault). This is a simple tcp chat app - and I am only looking to send strings bidirectionaly between client and server.
Server side below - the chat() function handles communication , after calling fgets , inputting my string , and attempting to send the data - I get an immediate (segmentation fault) and crash.
#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 <ifaddrs.h>
#define SA struct sockaddr
int chat(int sockfd, int port) {
for (;;) {
char *buffer_send;
char *buffer_recv;
recv(sockfd, buffer_recv, port , 0);
printf("%s", buffer_recv);
printf(":"); fgets(buffer_send, 512, stdin);
char* exit_func;
exit_func = strstr(buffer_send, "exit");
if (exit_func = strstr(buffer_send, "exit")) {
close(sockfd);
return 0;
} else {
send(sockfd, buffer_send, 512, 0);
}
}
}
int main () {
int server_socket, new_socket, c;
struct sockaddr_in socket_address, client;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
printf("socket creation failed! \n");
return 1;
} printf("socket created! \n");
socket_address.sin_addr.s_addr = inet_addr("192.168.0.10");
socket_address.sin_family = AF_INET;
socket_address.sin_port = (8003);
if( bind(server_socket,(struct sockaddr *)&socket_address , sizeof(socket_address)) < 0) {
printf("bind failed! \n");
return 1;
} printf("bind done! \n");
listen(server_socket , 3);
printf("Waiting for incoming connections...\n");
c = sizeof(struct sockaddr_in);
new_socket = accept(server_socket, (struct sockaddr *)&client, (socklen_t*)&c);
if (new_socket<0) {
printf("accept failed\n");
return 1;
} printf("connection accepted!\n");
chat(new_socket, socket_address.sin_port);
return 0;
}
however the same way of sending data on my client seems to work fine (without crashing while trying to send data):
#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 <ifaddrs.h>
int chat(int sockfd, int port) {
for (;;) {
char *buffer_send;
char *buffer_recv;
printf(":"); fgets(buffer_send, 512, stdin);
char* exit_func;
exit_func = strstr(buffer_send, "exit");
if (exit_func = strstr(buffer_send, "exit")) {
close(sockfd);
return 0;
} else {
send(sockfd, buffer_send, 512, 0);
}
recv(sockfd, buffer_recv, port , 0);
printf("%s", buffer_recv);
}
}
int main () {
int target_socket;
struct sockaddr_in target_server;
target_socket = socket(AF_INET, SOCK_STREAM, 0);
if (target_socket == -1) {
printf("socket creation failed!\n");
return 1;
} printf("socket created!\n");
target_server.sin_addr.s_addr = inet_addr("192.168.0.10");
target_server.sin_family = AF_INET;
target_server.sin_port = (8003);
if (connect(target_socket , (struct sockaddr *)&target_server , sizeof(target_server)) < 0) {
printf("connection failed!\n");
return 1;
} printf("connected!\n");
chat(target_socket, target_server.sin_port);
return 0;
}
You did not allocated the room for incoming messages, the same for the buffer you want to send. I expect to do some char buffer_send[512 + 1] = {}; and char buffer_recv[512 + 1] = {}; to make some place for the message content.
The + 1 is added for the extra safety, to not overwrite the NULL terminator when the message received is large enough to fill the entire allocated buffer.

Broadcasting Server to Client C

I am trying to broadcast a UDP message from the server to client. I would like for the server to send the broadcast to the client and then for the client to acknowledge the broadcast. They both compile with no errors but the server will not send the broadcast. The server says it successfully binds. Any tips would be helpful please.
Client.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#define PORT 8081
int main (int argc, char* argv[]){
int clientsocket;
int reuse = 1;
int reuseaddr;
int bind_sock;
int rec_broad;
int send_ack;
char dgram[512];
char client_message[2000];
struct sockaddr_in serv_address;
struct sockaddr_in group;
if (argc != 3) {
printf("Command line args should be multicast group and port\n");
printf("(e.g. for SSDP, `listener 239.255.255.250 1900`)\n");
return 1;
}
clientsocket = socket(AF_INET, SOCK_DGRAM, 0);
if(clientsocket < 0){
printf("\n\tSocket not created.\n");
exit(1);
}
else printf("\n\tSocket created successfully.\n");
reuseaddr = setsockopt(clientsocket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));
if(reuseaddr < 0){
printf("\n\tSetting REUSEADDR error.\n");
exit(1);
}
else printf("\n\tREUSEADDR Successful.\n");
serv_address.sin_family = AF_INET;
serv_address.sin_port = htons(PORT);
serv_address.sin_addr.s_addr = inet_addr(argv[1]);
/*bind_sock = bind(clientsocket, (struct sockaddr*) &serv_address, sizeof(serv_address));
if(bind_sock < 0){
printf("\n\tBind unsuccessful.\n");
exit(1);
}
else printf("\n\tBind Successful.\n");*/
strcpy(client_message, "Acknowledged.\n");
for(;;){
printf("\nListening........\n");
rec_broad = recvfrom(clientsocket, dgram, sizeof(dgram), 0, (struct sockaddr*) &serv_address, sizeof(serv_address));
if(rec_broad < 0){
printf("\n\tBroadcast not received.\n");
exit(1);
}
else printf("\n\tBroadcast received successfully.\n");
send_ack = sendto(clientsocket, client_message, sizeof(client_message), 0, (struct sockaddr*)&serv_address, sizeof(serv_address));
if (send_ack < 0){
printf("\n\tAck not sent.\n");
}
else printf("\n\tAcknowledge sent successfully.\n");
}
return 0;
}
Server.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8081
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
int main (int argc, char *argv[]){
int serv_socket;
struct sockaddr_in broadcast_addr;
struct sockaddr_in client_addr;
int b_addr_len;
int ret;
int bind_sock;
int yes = 1;
char buffer[2000];
int send_broad;
int z;
//Create socket
serv_socket = socket(AF_INET, SOCK_DGRAM, 0);
if(serv_socket < 0){
printf("\n\tProblem1.\n");
exit(1);
}
else printf("\n\tSocket made successful.\n");
//Setsockopt
ret = setsockopt(serv_socket, SOL_SOCKET, SO_BROADCAST, (char*)&yes, sizeof(yes));
if(ret < 0){
printf("\n\tSetsockopt error.\n");
return -1;
}
else printf("\n\tSetsockopt successful.\n");
b_addr_len = sizeof(broadcast_addr);
//Broadcast Address
memset((void*)&broadcast_addr, 0, b_addr_len);
broadcast_addr.sin_family = AF_INET;
broadcast_addr.sin_addr.s_addr = inet_addr(argv[1]);
broadcast_addr.sin_port = htons(atoi(argv[2]));
//Bind socket with client
bind_sock = bind(serv_socket, (struct sockaddr*) &client_addr, b_addr_len);
if (ret < 0){
printf("\n\tBind unsuccessful.\n");
exit(1);
}
else printf("\n\tBind successful.\n");
memset(buffer, '\0', 2000);
strcpy(buffer, "This is the broadcast!\n");
//Send broadcast
send_broad = sendto(serv_socket, buffer, sizeof(buffer), 0, (struct sockaddr*)&broadcast_addr, b_addr_len);
if(send_broad < 0){
printf("\n\tBroadcast not sent.\n");
exit(1);
}
else printf("\n\tBroadcast sent OK.\n");
return 0;
}

cannot establish server client connection - error 10061 in c winsock

I'm trying to run server client on my 2 computers in my local network at home.
The first computer is server and the second is client.
I have error 10061 when I'm trying to connect the server. ("error - connect failed. sockfd is 164, errno is 34, WSA is 10061").
error 10061 means -"connection refused. No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host — that is, one with no server application running."
I thought it might be firewall problem so I approved in my firewall the port Im using, but stil it doesnt work.
Also, both computer have the same IP(why is that?).
Here's my code:
server.c:
#include <sys/types.h>
#include <signal.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <tchar.h>
int socketBind(int sockfd, int port){
struct sockaddr_in serv_addr;
ZeroMemory((char*) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
if ( bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0 ){
// we can check errno for exact ERROR
printf("bind failed with errno %d\n",errno);fflush(NULL);
return ERROR;
}
if ( listen(sockfd, 100) == -1 ){
return ERROR;
}
return 1;
}
int main()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) == SOCKET_ERROR) {
printf ("Error initialising WSA.\n");
return -1;
}
int sockfd; // server's listening socket's descriptor id
int port = 4997;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
while ( sockfd < 0 ){ // ERROR
printf("Listener socket creation failed with:%d, errno is %d\n",sockfd,errno);fflush(NULL);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
}
if ( socketBind(sockfd, port) == ERROR ){
printf("Socket bind failed with errno=%d\n",errno);fflush(NULL);
close(sockfd);
return ERROR;
}
printf("Starting to listen to other USERS!\n");fflush(NULL);
struct sockaddr_in cli_addr;
int clilen = sizeof(cli_addr); // length of address
// accept() returns the socket that will be used for Control Connection with the accepted client
printf("*************Waiting for other USERS************\n");fflush(NULL);
int newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
int readLength;
char command[(128+1)];
while(1)
{
ZeroMemory(command, sizeof(command));
readLength = read(newsockfd, command, 128+1);
if(readLength <= 0)
{
continue;
}
if(readLength > 0)
{
printf(" here should be API's func to command %s", command);fflush(NULL);
}
else
{
close(sockfd);
close(newsockfd);
WSACleanup();
printf("Read failed with errno:%d\n",errno);fflush(NULL);
return ERROR;
}
}
close(sockfd);
close(newsockfd);
WSACleanup();
return 1;
}
client.c:
#include <sys/types.h>
#include <signal.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <winsock2.h>
#include <windows.h>
#include <tchar.h>
int verifyWrite(int sockfd, char* command){
int size = strlen(command);
int i=0, x=0;
for(i=0;i<size;){
x = write(sockfd, command, size);
if(x < 0){
return ERROR;
}
if(x >= 0) {
i += x;
}
}
return 0;
}
int sendToAll(char* message, int sockfd)
{
if ( verifyWrite(sockfd, message) < 0 )
{
printf("error while sending message\n");fflush(NULL);
}
return 0;
}
int main()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) == SOCKET_ERROR) {
printf ("Error initialising WSA.\n");
return -1;
}
int port,sockfd;
struct sockaddr_in serv_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0); //creating control connection
while(sockfd < 0){
printf("error - sockfd = %d\n",sockfd);fflush(NULL);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
}
port = 4997;
ZeroMemory((char*)&serv_addr, sizeof(serv_addr));
serv_addr.sin_addr.s_addr = inet_addr("192.168.1.20");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
while(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0){
printf("error - connect failed. sockfd is %d, errno is %d, WSA is %d\n",sockfd,errno,WSAGetLastError());fflush(NULL);
}
printf("\n opened connection to %s\n", "192.168.1.20");fflush(NULL);
int i = 0;
while(i< 6)
{
sendToAll("just a message", sockfd);
i++;
}
WSACleanup();
return 0;
}
Your server is listening on port 4997, but your client is connecting to port 80 instead. You would have caught that if you had included the listening and connecting IP:Port pairs in your debug output to the console.

Resources