c program client server - c

I have written a client and server c program, which I have taken from example code.
I want to write a iterative client and server program,
i.e. after client send a string, then the server print that string and then send back a string to client
then the client print the string inputted by server, and so on until the client input 'exit' to quit.
I have modified the code that the client and server is iterative
also, if client input 'exit', the program will quit
But I have a question, I don't know how to make the client to receive the string which is inputed by server, I only can make the server to receive the client's string
Please feel free to provide hints
Many thanks!
my code
client.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <winsock2.h>
#define SA struct sockaddr
#define S_PORT 4321
#define BufferStoreLEN 1024
void errexit(const char *format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
WSACleanup();
exit(1);
}
int main(int argc, char **argv)
{
WSADATA wsadata;
SOCKET sockfd, listenfd, connfd;
int i, n, q, len, alen, out;
char str[BufferStoreLEN+1];
char cmp[] = "exit";
char* BufferStore;
struct sockaddr_in servaddr, cliaddr;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
errexit("WSAStartup failed\n");
if (argc != 2)
errexit("wrong arg");
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET )
errexit("socket error: error number %d\n", WSAGetLastError());
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(S_PORT);
if ( (servaddr.sin_addr.s_addr = inet_addr(argv[1])) == INADDR_NONE)
errexit("inet_addr error: error number %d\n", WSAGetLastError());
if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR)
errexit("connect error: error number %d\n", WSAGetLastError());
do {
printf("Input: ");
scanf("%s", str);
out = htonl(strlen(str));
BufferStore = malloc(strlen(str));
for( i=0; i<strlen(str); i++)
BufferStore[i] = str[i];
out = send(sockfd, BufferStore, strlen(str), 0);
/*
if ( strcmp( cmp, str ) != 0 )
{
printf("Server's response:\n");
n = recv(connfd, BufferStore, BufferStoreLEN, 0);
while (n > 0) {
BufferStore[n] = '\0';
printf("%s\n", BufferStore);
n = recv(connfd, BufferStore, BufferStoreLEN, 0);
}
}*/
}while(strcmp(cmp,str)!=0);
closesocket(sockfd);
WSACleanup();
free(str);
free(BufferStore);
return 0;
}
server.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <winsock2.h>
#include <Windows.h>
#define SA struct sockaddr
#define MAXLINE 4096
#define S_PORT 4321
#define BufferStoreLEN 1024
void errexit(const char *format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
WSACleanup();
exit(1);
}
int main(int argc, char **argv)
{
WSADATA wsadata;
SOCKET listenfd, connfd;
SOCKET sockfd;
int number, out;
int i, n, q, alen;
struct sockaddr_in servaddr, cliaddr;
char BufferStore[BufferStoreLEN+1];
char* Store;
char str[BufferStoreLEN+1];
int flag = 1;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
errexit("WSAStartup failed\n");
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == INVALID_SOCKET)
errexit("cannot create socket: error number %d\n", WSAGetLastError());
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(S_PORT);
if (bind(listenfd, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR)
errexit("can't bind to port %d: error number %d\n", S_PORT, WSAGetLastError());
if (listen(listenfd, 5) == SOCKET_ERROR)
errexit("can't listen on port %d: error number %d\n", S_PORT, WSAGetLastError());
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET )
errexit("socket error: error number %d\n", WSAGetLastError());
for ( ; ; )
{
alen = sizeof(SA);
connfd = accept(listenfd, (SA *) &cliaddr, &alen);
if (connfd == INVALID_SOCKET)
errexit("accept failed: error number %d\n", WSAGetLastError());
n = recv(connfd, BufferStore, BufferStoreLEN, 0);
while (n > 0){
BufferStore[n] = '\0';
printf("%s\n", BufferStore);
printf("Input: ");
scanf("%s",str);
out = htonl(strlen(str));
Store = malloc(strlen(str));
for( q=0; q<strlen(str); q++)
Store[q] = str[q];
out = send(sockfd, Store, strlen(str), 0);
n = recv(connfd, BufferStore, BufferStoreLEN, 0);
}
closesocket(sockfd);
WSACleanup();
free(str);
free(BufferStore);
}
}

One thing that's important to understand about stream sockets (SOCK_STREAM) is that they present you with a stream of bytes (hence the name :-)), without any "packet boundaries".
Specifically, if you send() 100 bytes of data from the client, the server may recv() it as
one recv() call returning 100 bytes
two recv()s of 50 bytes each
one recv() 90 bytes followed by 10 recv()s of 1 byte
... etc ...
Your code appears to assume that what you send() on one end will be delivered in a single recv() call at the other end. For small chunks of data, that may work, but it's not something you can/should rely on.
In general, to do a command/response scenario like you're setting up, you need to have a way for the server to recognize "that's the end of the command, I should respond now". For example, if you're sending text strings, you can use a newline (\n) as the "end of command" marker.
The server would thus do multiple recv() calls (each one appending to a buffer) until it sees a \n (or an error), then send the response back; the client would do something similar when reading the response.

Your server is running inside an infinite loop, so to be able to send data that is input in the server application to the client application, you would have to read the user input in a different thread then send that to the user, as the infinite loop is currently blocking the current thread.

Related

read input & save in shared memory in Socket in C

I work on the server side Socket (use Telnet client) in Linux. Client input a line with command(GET/PUT/DEL, key and an associated value (spaces to seperate in between). This key-value pair is then passed accordingly on to the function(GET/PUT/DEL), which saves the data in the shared memory (keyValueStore).
Expected client side: (> is the output from Server)
GET key1
> GET:key1:key_nonexistent
PUT key1 value1
> PUT:key1:value1
PUT key2 value2
> PUT:key2:value2
DEL key2
> DEL:key2:key_deleted
Questions:
1/ i tried to use strtok() and keyValueStore to seperate & save the tokens in a normal c file, but how should I do (or transform) it into the data transfer communication between server and client?
2/ when or where should I call the command functions (e.g. int put(char* key, char* value) )? in server.c after reading the input but before giving output?
Any advices is appreicated. Thanks for your kindness!
server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFSIZE 1024 // Buffer Size
#define TRUE 1
#define PORT 5678
int main() {
int rfd; // Create-Descriptor
int cfd; // Connection-Descriptor (accept)
struct sockaddr_in client;
socklen_t client_len;
char in[BUFSIZE];
int bytes_read;
// 1. socket()
rfd = socket(AF_INET, SOCK_STREAM, 0);
if (rfd < 0 ){
fprintf(stderr, "Error\n");
exit(-1);
}
//Initialize the server address by the port and IP
struct sockaddr_in server;
memset(&server, '\0', sizeof(server));
server.sin_family = AF_INET; // Internet address family: v4 address
server.sin_addr.s_addr = INADDR_ANY; // Server IP address
server.sin_port = htons(PORT); // Server port
// 2. bind()
int brt = bind(rfd, (struct sockaddr *) &server, sizeof(server));
if (brt < 0 ){
fprintf(stderr, "Error\n");
exit(-1);
}
// 3. listen() = listen for connections
int lrt = listen(rfd, 5);
if (lrt < 0 ){
fprintf(stderr, "Error\n");
exit(-1);
}
while (1) {
// 4. accept()
cfd = accept(rfd, (struct sockaddr *) &client, &client_len);
// read() = read from a socket (Client's data)
bytes_read = read(cfd, in, BUFSIZE);
while (bytes_read > 0) {
printf("sending back the %d bytes I received...\n", bytes_read);
// write() = write data on a socket (Client's data)
write(cfd, in, bytes_read);
bytes_read = read(cfd, in, BUFSIZE);
}
close(cfd);
}
close(rfd);
}
Input.c
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#define MAX_ARRAY 100
int main() {
typedef struct Value_ {
char key[MAX_ARRAY];
char value[MAX_ARRAY];
} KeyStorage;
KeyStorage storageKey[MAX_ARRAY];
char client_input[MAX_ARRAY];
char *argv[3];
char *token;
int count = 0;
while (1) {
printf("Input: ");
gets(client_input);
//get the first token
token = strtok(client_input, " ");
int i = 0;
//walk through other tokens
while (token != NULL) {
argv[i] = token;
i++;
token = strtok(NULL, " ");
}
argv[i] = NULL; //argv ends with NULL
// arg[0] = command z.B. GET, PUT
printf("Commend: %s\n", argv[0]);
strcpy(storageKey[count].key, argv[1]);
printf("Key: %s\n", storageKey[count].key);
strcpy(storageKey[count].value, argv[2]);
printf("Value: %s\n", storageKey[count].value);
count++;
if (strcmp(argv[0], "QUIT") == 0) {
break;
}
}
return 0;
}
There are a number of errors in your code. I have fixed all to build a working example. Of course, this is not your complete application and there is even a lot of room for enhancements.
I developed and tested my code with MSVC2019 under Windows but I used a #define to isolate Windows specific code so it should compile and run correctly under Linux as well (I have not tested that).
The main problem your code had is a misunderstanding of TCP connection. It is a stream oriented connection and you must assemble "command lines" yourself, receiving one character at a time.
It is only when a line is complete that you can parse it to detect the command sent by the client. I made simple: only one command "exit" does something (close the connection). Everything else is simply ignored.
I made line assembling the easy way. That means that there is no edit possible. Backspace, delete, cursor keys and more and input as any other characters and doesn't work a a user would expect. You should take care of that.
Finally, I kept the code close to what you used. This code is single user. It accept a connection, accept commands from it and only accept a new connection once the first is closed. This is not normally the way to create a server program. To make it multiuser, you should use non-blocking socket and select() or use multi-threading.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#ifdef WIN32
#include <WinSock2.h>
#include <io.h>
typedef int socklen_t;
#pragma warning(disable : 4996) // No warning for deprecated function names such as read() and write()
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define closesocket close
#endif
#define BUFSIZE 1024 // Buffer Size
#define TRUE 1
#define PORT 5678
int main(int argc, char *argv[])
{
#ifdef WIN32
int iResult;
WSADATA wsaData;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
#endif
int rfd; // Create-Descriptor
int cfd; // Connection-Descriptor (accept)
struct sockaddr_in client;
socklen_t client_len;
char in[BUFSIZE];
int bytes_read;
// 1. socket()
rfd = socket(AF_INET, SOCK_STREAM, 0);
if (rfd < 0) {
fprintf(stderr, "Error\n");
exit(-1);
}
// Initialize the server address by the port and IP
struct sockaddr_in server;
memset(&server, '\0', sizeof(server));
server.sin_family = AF_INET; // Internet address family: v4 address
server.sin_addr.s_addr = INADDR_ANY; // Server IP address
server.sin_port = htons(PORT); // Server port
// 2. bind()
int brt = bind(rfd, (struct sockaddr*)&server, sizeof(server));
if (brt < 0) {
fprintf(stderr, "Error\n");
exit(-1);
}
// 3. listen() = listen for connections
int lrt = listen(rfd, 5);
if (lrt < 0) {
fprintf(stderr, "Error\n");
exit(-1);
}
while (1) {
client_len = sizeof(client);
cfd = accept(rfd, (struct sockaddr*)&client, &client_len);
if (cfd < 0) {
fprintf(stderr, "accept failed with error %d\n", WSAGetLastError());
exit(-1);
}
printf("Client connected\n");
while (1) {
/*
// Send prompt to client
char* prompt = "> ";
if (send(cfd, prompt, strlen(prompt), 0) <= 0) {
fprintf(stderr, "send() failed with error %d\n", WSAGetLastError());
exit(1);
}
*/
// read a line from a socket (Client's data)
int bytes_idx = -1;
while (1) {
if (bytes_idx >= (int)sizeof(in)) {
fprintf(stderr, "input buffer overflow\n");
break;
}
// Receive on byte (character) at a time
bytes_read = recv(cfd, &in[++bytes_idx], 1, 0);
if (bytes_read <= 0) // Check error or no data read
break;
/*
printf("sending back the %d bytes I received...\n", bytes_read);
if (send(cfd, &in[bytes_idx], 1, 0) <= 0) {
fprintf(stderr, "send() failed with error %d\n", WSAGetLastError());
exit(1);
}
*/
if (in[bytes_idx] == '\n') {
// Received a complete line, including CRLF
// Remove ending CR
bytes_idx--;
if ((bytes_idx >= 0) && (in[bytes_idx] == '\r'))
in[bytes_idx] = 0;
break;
}
}
if (bytes_idx > 0) { // Check for empty line
printf("Received \"%s\"\n", in);
// Check for client command
if (stricmp(in, "exit") == 0)
break;
else {
printf("Client sent unknown command\n");
}
}
}
closesocket(cfd);
printf("Client disconnected\n");
}
closesocket(rfd);
#ifdef WIN32
WSACleanup();
#endif
}

Address family not supported by protocol UDP C Error sending

I'm trying to implement communication by UDP protocol, and I'm getting an error: "Error sending: Address family not supported by protocol". I've checked in Google for this problem but couldn't managed to find answer.
Please be patient, I'm only starting my adventure with coding in C.
Here is a C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#define BUFLEN 512
// define function that deals with errors
void error(const char *msg)
{
perror(msg); // print error msg
exit(1); // exit the main() function
}
int main(int argc, char *argv[])
{
struct sockaddr_in serv1_addr, serv2_addr, cli1_addr, cli2_addr; //definicja struktur adresów servera i clienta
struct hostent *server; //defines host addres struct
int cl1_sockfd, se1_sockfd, se2_sockfd, i, c1len = sizeof(cli1_addr), c2len = sizeof(cli2_addr), recv_len, portno1,portno2; // creates inits
int cli1_len = sizeof(cli1_addr);
int cli2_len = sizeof(cli2_addr);
char buf[BUFLEN];
if (argc < 4) {
fprintf(stderr,"ERROR, no port provided\n"); // deal with wrong port
exit(1);
}
//tworzenie soceketu servera
if ((se1_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
error("socket1"); //if socket() return -1 -- error
}
if ((se2_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
error("socket2"); //if socket() return -1 -- error
}
//zero out the structure
memset( &serv1_addr, 0, sizeof(serv1_addr)); //put zero into structure
memset( &serv2_addr, 0, sizeof(serv2_addr)); //put zero into structure
portno1 = atoi(argv[2]); // get port number
portno2 = atoi(argv[3]);
serv1_addr.sin_family = AF_INET; // specify address family (IPv4)
serv1_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv1_addr.sin_port = htons(portno1); // set port number
serv2_addr.sin_family = AF_INET; // specify address family (IPv4)
serv2_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv2_addr.sin_port = htons(portno2); // set port number
if(connect(se1_sockfd,(struct sockaddr *) &serv1_addr, sizeof(serv1_addr)) < 0)
error ("ERROR connecting1"); //if connection failed
if(connect(se2_sockfd,(struct sockaddr *) &serv2_addr, sizeof(serv2_addr)) < 0)
error ("ERROR connecting2"); //if connection failed
while(1) //inf loop
{
printf("Please enter the message: "); //write the msg to socket
bzero(buf, 512); //fill buffer with zeros
fgets(buf, 512, stdin); //read into buffer
if( sendto( se1_sockfd, buf, BUFLEN, 0, (struct sockaddr*) &cli1_addr, cli1_len) < 0)
error ("Error sending1");
if( sendto( se2_sockfd, buf, BUFLEN, 0, (struct sockaddr*) &cli2_addr, cli2_len) < 0)
error ("Error sending2");
if (recvfrom(se1_sockfd, buf, BUFLEN, 0, (struct sockaddr *) &cli1_addr, &cli1_len) == -1){
error("recivfrom()1"); //if reciving failed -- error
}
printf("Data: %s\n", buf);
if (recvfrom(se2_sockfd, buf, BUFLEN, 0, (struct sockaddr *) &cli2_addr, &cli2_len) == -1){
error("recivfrom()2"); //if reciving failed -- error
}
printf("Data: %s\n", buf);
}
close(se1_sockfd);
close(se2_sockfd);
return 0;
}
Thanks for your help. ;)
Your issue is likely because of uninitialized destination address. sendto() takes destination address as the one before the last argument. But you are trying to provide not-initialized address (like for recvfrom())
if( sendto( se1_sockfd, buf, BUFLEN, 0, (struct sockaddr*) &cli1_addr, cli1_len) < 0)
error ("Error sending1");
^^^
Try serv1_addr instead ?
Also need to provide appropriate size.
One more thing. As long as you use sendto() - no need to perform connect(). UDP is connectionless and connect() only establishes default destination address for those who is going to use send() on such socket. But this is not your case because you provide destination address each time you call sendto(). Even more - you may use different addresses each time.
P.S. Reference: sendto()

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.

berkeley sockets, running simple client and server connecting

I'm just starting out on networking programming in c. I followed a simple tutorial to create a server which accepts a connection and prints out the message sent from the client.
the client takes an argument as the address of the server.
I'm not sure how to specify the address of the server? Is it my machine name?
I'm running the server in one terminal and trying to connect from another. Thanks for any help :)
here's the server code
`#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
#define BUFLEN 1500
int fd;
ssize_t i;
ssize_t rcount;
char buf[BUFLEN];
printf("test1");
fd = socket (AF_INET,SOCK_STREAM,0);
if (fd == -1){
printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
}
struct sockaddr_in addr;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
addr.sin_port = htons(500);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
printf("cannot bind socket");
}
if (listen(fd, 20) == -1) {
printf("unable to listen");
}
int connfd;
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
connfd = accept(fd, (struct sockaddr *) &cliaddr, &cliaddrlen);
if (connfd == -1) {
printf("unable to accept");
}
rcount = read(fd, buf, BUFLEN);
if (rcount == -1) {
// Error has occurred
}
for (i = 0; i < rcount; i++) {
printf("%c", buf[i]);
}
}`
printf("test1");
You should add "\n" (newline char) at the end of printed string, so that it prints immediately. Without "\n", printf() buffers its output, and you don't see them.
addr.sin_port = htons(500);
Ports 0 - 1023 are called "well known port" and reserved to the system (root). You should use port 1024 or greater for a test program like this. Changing it from 500 to 1500 (for example) binds successfully.
(You don't see the error message "cannot bind socket" because it has no "\n", as I said above.)
rcount = read(fd, buf, BUFLEN);
You should read from connfd, instead of fd. With these changes, it worked for me.
(I used "telnet localhost 1500" as a client.)

C Language: Why I cannot transfer file from server to client?

I want to ask, why I cannot transfer file from server to client?
When I start to send the file from server, the client side program has a problem. So, I spend some times to check the code, but I still cannot find out the problem
Can anyone point out the problem for me?
ps. Thanks for the administarator fix the code first.
ps2. I also want to know what is the error
When I execute the program, the client side program will "hang" without telling the reason.
It is difficult for me to trace the error...
thanks a lot!
client side code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <winsock2.h>
#include <direct.h>
#define SA struct sockaddr
#define S_PORT 5678
#define MAXLEN 1000
#define true 1
void errexit(const char *format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
WSACleanup();
exit(1);
}
int main(int argc, char *argv [])
{
WSADATA wsadata;
SOCKET sockfd;
int number,message;
char outbuff[MAXLEN],inbuff[MAXLEN];
char PWD_buffer[_MAX_PATH];
struct sockaddr_in servaddr;
FILE *fp;
int numbytes;
char buf[2048];
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
errexit("WSAStartup failed\n");
if (argc != 2)
errexit("client IPaddress");
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET )
errexit("socket error: error number %d\n", WSAGetLastError());
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(S_PORT);
if ( (servaddr.sin_addr.s_addr = inet_addr(argv[1])) == INADDR_NONE)
errexit("inet_addr error: error number %d\n", WSAGetLastError());
if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR)
errexit("connect error: error number %d\n", WSAGetLastError());
if ( (fp = fopen("C:\\users\\pc\\desktop\\COPY.c", "wb")) == NULL){
perror("fopen");
exit(1);
}
printf("Still NO PROBLEM!\n");
//Receive file from server
while(1){
numbytes = read(sockfd, buf, sizeof(buf));
printf("read %d bytes, ", numbytes);
if(numbytes == 0){
printf("\n");
break;
}
numbytes = fwrite(buf, sizeof(char), numbytes, fp);
printf("fwrite %d bytes\n", numbytes);
}
fclose(fp);
close(sockfd);
return 0;
}
server side code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <stdarg.h>
#include <winsock2.h>
#include <direct.h>
#include <io.h>
#define SA struct sockaddr
#define S_PORT 5678
#define MAXLEN 1000
void errexit(const char *format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
WSACleanup();
exit(1);
}
int main(int argc, char *argv [])
{
WSADATA wsadata;
SOCKET listenfd, connfd;
int number, message, numbytes;
int h, i, j, alen;
int nread;
struct sockaddr_in servaddr, cliaddr;
FILE *in_file, *out_file, *fp;
char buf[4096];
if (WSAStartup(MAKEWORD(2,2), &wsadata) != 0)
errexit("WSAStartup failed\n");
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == INVALID_SOCKET)
errexit("cannot create socket: error number %d\n", WSAGetLastError());
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(S_PORT);
if (bind(listenfd, (SA *) &servaddr, sizeof(servaddr)) == SOCKET_ERROR)
errexit("can't bind to port %d: error number %d\n", S_PORT, WSAGetLastError());
if (listen(listenfd, 5) == SOCKET_ERROR)
errexit("can't listen on port %d: error number %d\n", S_PORT, WSAGetLastError());
alen = sizeof(SA);
connfd = accept(listenfd, (SA *) &cliaddr, &alen);
if (connfd == INVALID_SOCKET)
errexit("accept failed: error number %d\n", WSAGetLastError());
printf("accept one client from %s!\n", inet_ntoa(cliaddr.sin_addr));
fp = fopen ("client.c", "rb"); // open file stored in server
if (fp == NULL) {
printf("\nfile NOT exist");
}
//Sending file
while(!feof(fp)){
numbytes = fread(buf, sizeof(char), sizeof(buf), fp);
printf("fread %d bytes, ", numbytes);
numbytes = write(connfd, buf, numbytes);
printf("Sending %d bytes\n",numbytes);
}
fclose (fp);
closesocket(listenfd);
closesocket(connfd);
return 0;
}
Have you tried running the program under the debugger both on the client and server side to see where it hangs? I would check first if any bytes are sent and then work from there.
There are a couple of problems I noticed with the code that might or might not trigger this behaviour:
You're using write() to send data down a socket. The correct socket function would be send(), not write(). Keep in mind that send() might send fewer bytes than you asked it to so you might have to check and loop to get the whole buffer sent.
Same goes for the client, you want to use recv() and not read().
Both send() and recv() return -1 if there was any sort of problem. You need to handle this condition and preferably also check what the actual error was.
Socket programming is different from using plain files and there are a few more pitfalls due to the network generally being a little more flaky than your average file system.
You're also closing a socket using close(), not closesocket() in client.

Resources