#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h> //Unable to find all of this header files
#include <signal.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <netdb.h>
I want to use this header files ion my program and i cannot find it on the internet please provide a source from which i could get them
On windows, socket api is packed into a different set of headers. But the way the windows sockets work (if used in a "portable" way) is pretty much the same as on unix systems. Give or take.
The example code from the other question you linked looks like this on windows:
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
//#include <netinet/in.h>
#include <WinSock2.h>
#include <Ws2tcpip.h>
//#include <sys/wait.h>
//#include <sys/socket.h>
//#include <signal.h>
#include <ctype.h>
//#include <arpa/inet.h>
//#include <netdb.h>
#define PORT 20000
#define LENGTH 512
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
/* Variable Definition */
SOCKET sockfd;
char revbuf[LENGTH];
struct sockaddr_in remote_addr;
/* Get the Socket file descriptor */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor! (errno = %d)\n", errno);
exit(1);
}
/* Fill the socket address struct */
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr);
ZeroMemory(&(remote_addr.sin_zero), 8);
/* Try to connect the remote */
if (connect(sockfd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "ERROR: Failed to connect to the host! (errno = %d)\n", errno);
exit(1);
}
else
printf("[Client] Connected to server at port %d...ok!\n", PORT);
/* Send File to Server */
//if(!fork())
//{
char* fs_name = "/home/aryan/Desktop/quotidiani.txt";
char sdbuf[LENGTH];
printf("[Client] Sending %s to the Server... ", fs_name);
FILE *fs = NULL;
errno_t err = fopen_s(&fs, fs_name, "r");
if (fs == NULL)
{
printf("ERROR: File %s not found.\n", fs_name);
exit(1);
}
ZeroMemory(sdbuf, LENGTH);
int fs_block_sz;
while ((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
{
if (send(sockfd, sdbuf, fs_block_sz, 0) < 0)
{
fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", fs_name, errno);
break;
}
ZeroMemory(sdbuf, LENGTH);
}
printf("Ok File %s from Client was Sent!\n", fs_name);
//}
/* Receive File from Server */
printf("[Client] Receiveing file from Server and saving it as final.txt...");
char* fr_name = "/home/aryan/Desktop/progetto/final.txt";
FILE *fr = NULL;
err = fopen_s(&fr, fr_name, "a");
if (fr == NULL)
printf("File %s Cannot be opened.\n", fr_name);
else
{
ZeroMemory(revbuf, LENGTH);
int fr_block_sz = 0;
while ((fr_block_sz = recv(sockfd, revbuf, LENGTH, 0)) > 0)
{
int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
if (write_sz < fr_block_sz)
{
error("File write failed.\n");
}
ZeroMemory(revbuf, LENGTH);
if (fr_block_sz == 0 || fr_block_sz != 512)
{
break;
}
}
if (fr_block_sz < 0)
{
if (errno == EAGAIN)
{
printf("recv() timed out.\n");
}
else
{
fprintf(stderr, "recv() failed due to errno = %d\n", errno);
}
}
printf("Ok received from server!\n");
fclose(fr);
}
//close(sockfd);
closesocket(sockfd);
printf("[Client] Connection lost.\n");
return (0);
}
Now you can compare and see what is the same and what is a bit different. Hope that helps you to understand.
In case, you wonder next, why you have linker errors: Link against ws2_32.lib. In contrast to unix systems, where sockets are part of "libc", sockets are factored out into a separate dll in windows.
Related
I'm trying to write a C program for a client which can download a file from the server using TCP. The client will print and save the file content after it receives the file from the server. To compile the client program it needs IP address and port number of the server. I implemented it in Linux but it displayed 0s after the received texts. The saved text file was the same. I have no idea how to output the text only. Maybe there are wrongs in the receive buffer?
Code for server:
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#define portnum 12345
#define FILE_SIZE 500
#define BUFFER_SIZE 1024
void *client_fun(void * fd);
int main()
{
int new_fd;
pthread_t thread_id;
int server_fd=socket(AF_INET,SOCK_STREAM,0);
if(-1==server_fd)
{
perror("socket");
exit(1);
}
struct sockaddr_in server_addr;
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(portnum);
(server_addr.sin_addr).s_addr=htonl(INADDR_ANY);
if(-1==bind(server_fd,(struct sockaddr *)&server_addr,sizeof(server_addr)))
{
perror("bind");
close(server_fd);
exit(6);
}
if(-1==listen(server_fd,5))
{
perror("listen");
close(server_fd);
exit(7);
}
while(1)
{
struct sockaddr_in client_addr;
int size=sizeof(client_addr);
new_fd=accept(server_fd,(struct sockaddr *)&client_addr,&size);
if(new_fd < 0)
{
perror("accept");
continue;
}
printf("accept client ip锛?s:%d\n",inet_ntoa(client_addr.sin_addr),client_addr.sin_port);
//printf("new_fd=%d\n",new_fd);
if (new_fd > 0)
{
pthread_create(&thread_id, NULL, client_fun, (void *)&new_fd);
pthread_detach(thread_id);
}
}
close(server_fd);
return 0;
}
void *client_fun(void *arg)
{
int new_fd = *((int *)arg);
int file2_fp;
int len;
char buffer[BUFFER_SIZE];
memset( buffer,0, sizeof(buffer) );
while(1)
{
if((len=recv(new_fd, buffer, sizeof(buffer), 0)) <= 0)
{
continue;
}
char file_name[FILE_SIZE];
memset( file_name,0, sizeof(file_name) );
strncpy(file_name, buffer, strlen(buffer)>FILE_SIZE?FILE_SIZE:strlen(buffer));
memset( buffer,0, sizeof(buffer) );
printf("Client requests file %s\n", file_name);
if( strcmp(file_name,"exit")==0 )
{
break;
}
file2_fp = open(file_name,O_RDONLY,0777);
if(file2_fp<0)
{
printf("File %s Not Found\n", file_name);
char* err_info = "File not found\n";
if (write(new_fd, err_info, sizeof(err_info)) < 0)
{
printf("Send error information failed\n");
break;
}
continue;
}
else
{
int length = 0;
memset( buffer,0, sizeof(buffer) );
while( (length = read(file2_fp, buffer, sizeof(buffer))) > 0 )
{
if( write(new_fd, buffer, length) < 0)
{
printf("Send File %s Failed.\n", file_name);
break;
}
memset( buffer,0, sizeof(buffer) );
}
close(file2_fp);
printf("Transfer file %s successfully!\n", file_name);
}
}
close(new_fd);
}
Code for client:
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
int main(int argc, char *argv[])
{
int sockfd = 0;
char recvBuff[1024];
char file_name[500];
char *serverIP=argv[1];
int portno=atoi(argv[2]);
printf("IP Addresses: %s Port Number: %s\n", argv[1], argv[2]);
memset(recvBuff,'0',sizeof(recvBuff));
struct sockaddr_in server_addr;
/* Creat a socket*/
sockfd = socket(AF_INET, SOCK_STREAM, 0);
/*Initialize sockaddr_in structure*/
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(portno);
(server_addr.sin_addr).s_addr=inet_addr(serverIP);
/*Attempt a connection*/
printf("Connect status: ");
if (connect(sockfd,(struct sockaddr *)&server_addr,sizeof(server_addr))<0)
{
printf("fail\n");
return 0;
}
printf("success\n");
/*Request file from server*/
while(1)
{
printf("Input the file name to be requested from the server: ");
fgets(file_name,500, stdin);
char *p=strchr(file_name,'\n');
if (p) *p=0;
if (send(sockfd, file_name, strlen(file_name), 0)<0)
{
printf("Send failed.\n");
break;
}
printf("Send success.\n");
if (strcmp(file_name,"exit")==0)
break;
int length=0;
printf("Send status: ");
if (length=read(sockfd, recvBuff, sizeof(recvBuff))<0)
{
printf("fail\n");
continue;
}
else if (strcmp(recvBuff,"File not found\n")==0)
{
printf("fail\n");
continue;
}
else
{
printf("success\n");
/*Create file where text will be stored*/
FILE *fp;
fp=fopen("received_file.txt","w");
printf("Open file status: ");
if (fp==NULL)
{
printf("fail\n");
continue;
}
printf("success\n");
printf("Received text: ");
if (fprintf(fp, "%s", recvBuff)<0)
{
printf("Save status: fail\n");
continue;
}
fflush(fp);
printf("%s",recvBuff);
memset(recvBuff,0,1024);
while ((length=read(sockfd, recvBuff, sizeof(recvBuff)))>0)
{
if (fprintf(fp, "%s", recvBuff)<0)
{
printf("Save status: fail\n");
break;
}
fflush(fp);
printf("%s",recvBuff);
memset(recvBuff,0,1024);
}
printf("Save status: success");
}
}
}
Another question is that the client is supposed to keep asking for files until it sends an 'exit'. But it stopped asking the client to input the file name after the first file was received. What's wrong with the loop?
you have several issues.
first: - comparison operator has precedence over assignment so length gets FALSE(0) value instead of the real number of received data
if (length=read(sockfd, recvBuff, sizeof(recvBuff))<0)
it should be:
if ((length=read(sockfd, recvBuff, sizeof(recvBuff)))<0)
second: you are operating with zero terminated strings but you do not send zero ('\0') from server and client does not set it at the end of the data block.
So you need to set it explicitly at client side here
if ((length=read(sockfd, recvBuff, sizeof(recvBuff)))<0)
{
printf("fail\n");
continue;
}
else if (strcmp(recvBuff,"File not found\n")==0)
{
printf("fail\n");
continue;
}
else
{
recvBuff[length]='\0';
and here:
while ((length=read(sockfd, recvBuff, sizeof(recvBuff)))>0){
recvBuff[length]='\0';
I am receiving more bytes than I am sending on server side, and the file I receive has some garbage characters at the start of my file.
client code
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <dirent.h>
#include <time.h>
int main() {
int serverPort, clientPort, clientSock, serverSock;
scanf("%d", &clientPort);
struct sockaddr_in cadd, sadd1, sadd2, clen, slen;
cadd.sin_family = AF_INET;
cadd.sin_addr.s_addr = inet_addr("127.0.0.1");
cadd.sin_port = htons(clientPort);
clientSock = socket(AF_INET, SOCK_STREAM, 0);
if(clientSock == -1)
fprintf(stderr, "unable to create socket: %s\n", strerror(errno));
int result = connect(clientSock, (struct sockaddr *)&cadd, sizeof(cadd) );
if(result == -1) {
fprintf(stderr, "unable to create socket: %s\n", strerror(errno));
return -1;
}
while(1) {
struct stat stat_buf;
off_t offset = 0;;
int choice = 1;
int fd = open("myList.txt", O_RDONLY);
if (fd == -1) {
fprintf(stderr, "unable to open %s", strerror(errno));
exit(1);
}
fstat(fd, &stat_buf);
offset = 0;
int size = (int)stat_buf.st_size;
printf("File size: %d\n", size);
send(clientSock, &size, sizeof(stat_buf.st_size), 0);
int sent = sendfile(clientSock, fd, &offset, stat_buf.st_size);
if(sent == -1) {
fprintf(stderr, "error sendfile: %s\n", strerror(errno));
exit(1);
}
if(sent != stat_buf.st_size) {
fprintf(stderr, "error sendfile %d of %d bytes\n", sent, (int)stat_buf.st_size);
exit(1);
}
printf("sendfile succesfull %d\n", sent);
break;
}
}
server code
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <dirent.h>
#include <time.h>
int main() {
int serverPort, sock;
printf("Enter port number: ");
scanf("%d", &serverPort);
struct sockaddr_in server1, server2;
int addrlen = sizeof(server2);
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1) {
fprintf(stderr, "unable to create socket: %s\n", strerror(errno));
exit(1);
}
server1.sin_family = AF_INET;
server1.sin_port = htons(serverPort);
int rc = bind(sock, (struct sockaddr *) &server1, sizeof(server1));
if(rc == -1) {
fprintf(stderr, "bind error: %s\n", strerror(errno));
close(rc);
exit(1);
}
rc = listen(sock, 1);
if(rc == -1) {
fprintf(stderr, "listen failed: %s\n", strerror(errno));
exit(1);
}
while(1) {
int con = accept(sock, (struct sockaddr *) &server2, &addrlen);
int crt = creat("please.txt", S_IRWXU), size, count = 0;
recv(con, &size, sizeof(size), 0);
while(1) {
char mssg[100];
memset(mssg, '\0', sizeof(mssg));
int n = recv(con, mssg, sizeof(mssg), 0);
int wrt = write(crt, mssg, n);
count = count + wrt;
printf("Count: %d\n", count);
if(count >= size)
break;
}
printf("Write successful\n");
}
}
Attaching the screen-shots
client send =>
[server recv] =>
In the client you do this:
send(clientSock, &size, sizeof(stat_buf.st_size), 0);
But in the server you do:
recv(con, &size, sizeof(size), 0);
size is an int, which is 4 bytes. But st_size is off_t, which is presumably 8 bytes. So you're only reading the first 4 bytes of the the size, and leaving the rest to be copied into the file. That's why you end up with 4 extra bytes on the server.
Declare size with the same data type as st_size, rather than int, and your problem should be solved.
I am writing simple client-server program. Essentially I am following example from "Linux Network Programming" book. This is simple TCP server
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <netdb.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#define SERVERPORT 8888
#define MAXBUF 1024
int main(int argc, char* argv[])
{
int socket1, socket2;
int addrlen;
struct sockaddr_in fServer, fClient;
int status;
socket1=socket(AF_INET, SOCK_STREAM, 0);
if(socket1==-1)
{
printf("Could not create the socket\n");
exit(1);
}
fServer.sin_family=AF_INET;
fServer.sin_addr.s_addr=INADDR_ANY;
fServer.sin_port= htons(SERVERPORT);
status=bind(socket1, (struct sockaddr*) &fServer,
sizeof(fServer));
if(status==-1)
{
printf("could not bind the socket\n");
exit(1);
}
else printf("socket is created\n");
status=listen(socket1, 5);
if(status==-1)
{
printf("could not listen socket\n");
exit(1);
}
else printf("socket is waiting for connection\n");
for(;;)
{
int fd;
int i, readCounter, writeCounter;
char* bufptr;
char buf[MAXBUF];
char filename[MAXBUF];
addrlen=sizeof(fClient);
socket2=accept(socket1, (struct sockaddr*) &fClient, &addrlen);
if(socket2==-1)
{
printf("could not accept connection\n");
exit(1);
}
else printf("connection established, waiting for the file name\n");
i=0;
if((readCounter=read(socket2, filename, MAXBUF))>0)
i+=readCounter;
filename[i+1]='\0';
printf("reading from the file\n");
fd=open(filename, O_RDONLY);
if(fd==-1)
{
printf("could not open the file\n");
perror(" error is detected: ");
close(socket2);
continue;
}
else printf("file name is recieved, started copying\n");
readCounter=0;
while((readCounter=read(fd, buf, MAXBUF))>0)
{
writeCounter=0;
bufptr=buf;
while(writeCounter<readCounter)
{
readCounter-=writeCounter;
bufptr+=writeCounter;
writeCounter=write(socket2, bufptr, readCounter);
if(writeCounter==-1)
{
printf("could not write the file to client\n");
close(socket2);
continue;
}
}
}
close(fd);
close(socket2);
}
close(socket1);
return 0;
}
This code is for client.
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#define SERVERPORT 8888
#define MAXBUF 1024
int main(int argc, char* argv[])
{
int sockd;
int counter;
int fd;
struct sockaddr_in fServer;
char buf[MAXBUF];
int status;
if(argc<3)
{
printf("Incorrect data provided\n");
exit(1);
}
sockd=socket(AF_INET, SOCK_STREAM,0);
if(sockd==-1)
{
printf("could not create socket\n");
exit(1);
}
fServer.sin_family=AF_INET;
fServer.sin_addr.s_addr=inet_addr(argv[1]);
fServer.sin_port=htons(SERVERPORT);
status=connect(sockd, (struct sockaddr*)&fServer,
sizeof(fServer));
if(status==-1)
{
printf("could not connect to server\n");
exit(1);
}
status=write(sockd, argv[2], strlen(argv[2]+1));
if(status==-1)
{
printf("could not send file name to server\n");
exit(1);
}
shutdown(sockd, SHUT_WR);
fd=open(argv[2], O_WRONLY| O_CREAT| O_APPEND);
if(fd==-1)
{
printf("could not open destination file\n");
exit(1);
}
while((counter=read(sockd, buf, MAXBUF))>0)
{
write(fd, buf, counter);
}
if(counter==-1)
{
printf("file transfer is complete\n");
exit(1);
}
printf("file transfer is complete\n");
close(sockd);
return 0;
}
I pass file name from the same directory as server. I pass filename as agrc[2] parameter. Server oputput however is the following
socket is created
socket is waiting for connection
connection established, waiting for the file name
reading from the file
could not open the file
error is detected: : No such file or directory
connection established, waiting for the file name
reading from the file
could not open the file
error is detected: : No such file or directory
I entered the filename on my first attempt, then I enterd full path but still recieving the same message. So what is the problem? thanks in advance
Client:
status=write(sockd, argv[2], strlen(argv[2]+1));
strlen(argv[2]+1) should be strlen(argv[2])+1 if you want to include the \0.also: you do not close your fd. close(sockd); should be close(fd);
Server:
filename[i+1]='\0'; should be filename[i]='\0'; if you are not sure you received the \0.
if you are sending 1 char, for example 'a', i would be 1 and your array would look like
filename[0] = 'a'
filename[i] = undefined
filename[i+1] = '\0'
Unrelated to your problem, but on the server side you should advance bufptr after write(), not before.
Also: TCP is a stream protocol; there is no guarantee that a write() on one end of a connection will be completely read by a single recv() on the other end.
I am writing a simple client server program using unix domain sockets, but am having issues with the recv() call in my client program.
The program executes as follows:
Server sets up socket and waits for a connection
Client connects and sends a string
Server receives string, and sends string back to client (like an echo)
Client recv() call fails, returning "resource temporarily unavailable"
Client exits
Server waits for another connection
I have also tried using a poll() call in my client to wait for the response from the server.
In this case however, the recv() call simply receives a 0, implying the connection has been closed serverside, which it has not.
I have exhausted google on this error, but no fixes I came accross seem applicable to my code.
I have included my client (with poll() code commented out) and server code below.
I'm probably missing something obvious... but any insight would be greatly appreciated!
Server code:
/*
* testServer.c
*
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <termios.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <linux/spi/spidev.h>
#include <linux/sockios.h>
#include <errno.h>
#define SOCK_PATH "/var/run/ts.serv"
void handleSockIO(int *sockDesc);
int main ()
{
int sock;
struct sockaddr_un sock_addr;
int len, p;
struct pollfd poll_fd[1];
printf("[TS] testServer Started.\r\n");
if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
{
perror("[TS]wr_sock creation");
}
else
{
printf("[TS] Created socket descriptor.\r\n");
}
sock_addr.sun_family = AF_UNIX;
strcpy(sock_addr.sun_path, SOCK_PATH);
unlink(sock_addr.sun_path);
len = strlen(sock_addr.sun_path) + sizeof(sock_addr.sun_family);
if (bind(sock, (struct sockaddr *)&sock_addr, len) == -1)
{
perror("[TS]sock bind failed\r\n");
}
else
{
printf("[TS] Bound socket to sock_addr.\r\n");
}
if (listen(sock, 5) == -1)
{
perror("[TS] sock listen fail");
}
else
{
printf("[TS] Socket now listening.\r\n");
}
poll_fd[0].fd = sock;
poll_fd[0].events = POLLIN;
printf("[TS] Waiting for a connection...\r\n");
while (1)
{
p = poll(poll_fd, 1, 1); //Wait for 1 ms for data
if (p == -1)
{
perror("[TS] Poll");
}
else if (p == 0)
{
//printf("Timeout occurred!\n");
}
else
{
if (poll_fd[0].revents & POLLIN)//Data available to read without blocking
{
printf("[TS] Data available on sock..\r\n");
handleSockIO(&sock);
printf("[TS] Waiting for another connection...\r\n");
}
}
}//While(1)
return 0;
}
void handleSockIO(int *sockDesc)
{
int ioSock, n;
socklen_t t;
struct sockaddr_un remote_addr;
char str[15];
memset(str, ' ', sizeof(str));
t = sizeof(remote_addr);
if ((ioSock = accept(*sockDesc, (struct sockaddr *)&remote_addr, &t)) == -1)
{
perror("accept failed\r\n");
}
else
{
printf("[TS] Receiving...\r\n");
n = recv(ioSock, str, sizeof(str), 0);
if (n < 0)
printf("[TS] recvfrom failed: %s\r\n", strerror(errno));
else if(n == 0)
{
printf("[TS] Received %d on ioSock...\r\n", n);
}
else if(n > 0)
{
printf("[TS] Received: %s, which is %d long.\r\n", str, strlen(str));
printf("[TS] Echoing response...\r\n");
if (send(ioSock, str, n, 0) == -1) //Echo str back
{
printf("[TS] send failed: %s\r\n", strerror(errno));
}
else
{
printf("[TS] Send successful\r\n");
}
//============Wait to close IO descriptor=================
int r;
char temp[1]; //Arbitrary buffer to satisfy recv()
do
{
printf("[TS] Waiting for client to close connection...\r\n");
r = recv(ioSock, temp, sizeof(temp), 0);
if (r == 0)
{
printf("[TS] Client closed connection, closing ioSock...\r\n");
close(ioSock);
}
} while (r != 0);
//========================================================
}//if(n>0) else...
}
}
Client code:
/*
* testClient.c
*
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <termios.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <linux/sockios.h>
#include <errno.h>
#define CHAR_BUF_SIZE 15
#define SEND_STRING "Hello!"
#define SOCK_PATH "/var/run/ts.serv"
int main ()
{
char str[CHAR_BUF_SIZE] = {0};
int c, len, n, p;
int s; // s will hold a socket descriptor returned by socket()
struct sockaddr_un serv_addr;
struct pollfd poll_fd[1];
printf("[TC] testClient Started.\r\n");
//===============SOCKET SETUP===============================
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
{
printf("[TC] Socket failed: %s\r\n", strerror(errno));
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sun_family = AF_UNIX;
strcpy(serv_addr.sun_path, SOCK_PATH);
len = strlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family);
//==========================================================
// printf("[TC]Trying to connect to TS socket...\r\n");
//===============RESPONSE POLL SETUP========================
poll_fd[0].fd = s;
poll_fd[0].events = POLLIN;
//==========================================================
printf("[TC] Connecting to SOCK_PATH...\r\n");
c = connect(s, (struct sockaddr *)&serv_addr, len);
if (c == -1)
{
printf("[TC] Connection failed: %s\r\n", strerror(errno));
}
else
{
printf("[TC] Connected. Sending string....\r\n");
if (send(s, SEND_STRING, strlen(SEND_STRING), 0) == -1)
{
printf("[TC] send() failed: %s\r\n", strerror(errno));
}
else
{
printf("[TC] Send on SOCK_PATH successful.\r\n");
//Sending complete------------------------------------------------
//Wait for response...
printf("[TC] Waiting for server response...\r\n");
// p = poll(poll_fd, 1, -1); //Wait for a response
//
// if (p == -1)
// {
// perror("[TC] Poll");
// }
// else
// {
// if(poll_fd[0].revents & POLLIN)
// {
n = recv(s, str, sizeof(str), 0);
if (n < 0)
{
printf("[TC] Receive on SOCK_PATH failed: %s\r\n",
strerror(errno));
}
else if(n == 0)
{
printf("[TC] %d Received on SOCK_PATH.\r\n", n);
}
else if(n > 0)
{
printf("[TC] Received %d from SOCK_PATH: %s\r\n",
n, str);
}
// }
// }
}//if(send())
}//if(connect())
printf("[TC] Transction complete, closing connection and exiting.\r\n");
close(s);
return 0;
}
len = sizeof(serv_addr) instead of len = strlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family) should solve you problem. Also do not ignore compiler warnings, say n = recv(s, str, strlen(str), 0) with n declared as int and ssize_t returned by recv. It will help you to avoid a future errors.
I am sending hello.c file from the client to the server. The server receives it and stores it as hello123.c. I am trying to compile this file and run it using the system() command.
/* Server program*/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <signal.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <netdb.h>
#define PORT 20001
#define BACKLOG 5
#define LENGTH 512
int main ()
{
int sockfd;
int nsockfd;
int num;
int sin_size;
struct sockaddr_in addr_local; /* client addr */
struct sockaddr_in addr_remote; /* server addr */
char revbuf[LENGTH];
/* Get the Socket file descriptor */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 )
{
fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Obtaining socket descriptor successfully.\n");
/* Fill the client socket address struct */
addr_local.sin_family = AF_INET; // Protocol Family
addr_local.sin_port = htons(PORT); // Port number
addr_local.sin_addr.s_addr = INADDR_ANY; // AutoFill local address
bzero(&(addr_local.sin_zero), 8); // Flush the rest of struct
/* Bind a special Port */
if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 )
{
fprintf(stderr, "ERROR: Failed to bind Port. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Binded tcp port %d in addr 127.0.0.1 sucessfully.\n",PORT);
/* Listen remote connect/calling */
if(listen(sockfd,BACKLOG) == -1)
{
fprintf(stderr, "ERROR: Failed to listen Port. (errno = %d)\n", errno);
exit(1);
}
else
printf ("[Server] Listening the port %d successfully.\n", PORT);
int success = 0;
while(success == 0)
{
sin_size = sizeof(struct sockaddr_in);
/* Wait a connection, and obtain a new socket file despriptor for single connection */
if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, &sin_size)) == -1)
{
fprintf(stderr, "ERROR: Obtaining new Socket Despcritor. (errno = %d)\n", errno);
exit(1);
}
else
printf("[Server] Server has got connected from %s.\n", inet_ntoa(addr_remote.sin_addr));
char buffer[256];
bzero(buffer,256);
int n = 0;
n = read(nsockfd, buffer, 255);
if (n < 0) error("ERROR reading from socket");
printf("msg: %s\n",buffer);
/*Receive File from Client */
char* fr_name = "hello123.c";
FILE *fr = fopen(fr_name, "a");
if(fr == NULL)
printf("File %s Cannot be opened file on server.\n", fr_name);
else
{
bzero(revbuf, LENGTH);
int fr_block_sz = 0;
while((fr_block_sz = recv(nsockfd, revbuf, LENGTH, 0)) > 0)
{
int write_sz = fwrite(revbuf, sizeof(char), fr_block_sz, fr);
if(write_sz < fr_block_sz)
{
error("File write failed on server.\n");
}
bzero(revbuf, LENGTH);
if (fr_block_sz == 0 || fr_block_sz != 512)
{
break;
}
}
if(fr_block_sz < 0)
{
if (errno == EAGAIN)
{
printf("recv() timed out.\n");
}
else
{
fprintf(stderr, "recv() failed due to errno = %d\n", errno);
exit(1);
}
}
printf("Ok received from client!\n");
system("gcc hello123.c -o hello123.out");
system("./hello123.out");
fclose(fr);
}
}
}
/* Client program*/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <signal.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <netdb.h>
#define PORT 20001
#define LENGTH 512
int main(int argc, char *argv[]){
int sockfd;
int nsockfd;
char revbuf[LENGTH];
struct sockaddr_in remote_addr;
/* Get the Socket file descriptor */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "ERROR: Failed to obtain Socket Descriptor! (errno = %d)\n",errno);
exit(1);
}
/* Fill the socket address struct */
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr);
bzero(&(remote_addr.sin_zero), 8);
/* Try to connect the remote */
if (connect(sockfd, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "ERROR: Failed to connect to the host! (errno = %d)\n",errno);
exit(1);
}
else
printf("[Client] Connected to server at port %d...ok!\n", PORT);
/* Send File to Server */
//if(!fork())
//{
char* fs_name = "hello.c";
char sdbuf[LENGTH];
char buffer[256];
int n;
fgets(buffer,255,stdin);
// bzero(buffer,256);
n = write(sockfd,buffer, strlen(buffer));
if(n<0) printf("Error: sending filename");
printf("[Client] Sending %s to the Server... ", fs_name);
FILE *fs = fopen(fs_name, "r");
if(fs == NULL)
{
printf("ERROR: File %s not found.\n", fs_name);
exit(1);
}
bzero(sdbuf, LENGTH);
int fs_block_sz;
while((fs_block_sz = fread(sdbuf, sizeof(char), LENGTH, fs)) > 0)
{
if(send(sockfd, sdbuf, fs_block_sz, 0) < 0)
{
fprintf(stderr, "ERROR: Failed to send file %s. (errno = %d)\n", fs_name, errno);
break;
}
bzero(sdbuf, LENGTH);
}
printf("Ok File %s from Client was Sent!\n", fs_name);
//}
close (sockfd);
printf("[Client] Connection lost.\n");
return (0);
}
But I am getting an error as follows:
hello123.c:7:6: error: redefinition of ‘main’
hello123.c:2:6: note: previous definition of ‘main’ was here
hello123.c:12:6: error: redefinition of ‘main’
hello123.c:2:6: note: previous definition of ‘main’ was here
hello123.c:17:6: error: redefinition of ‘main’
hello123.c:2:6: note: previous definition of ‘main’ was here
hello123.c:22:6: error: redefinition of ‘main’
hello123.c:2:6: note: previous definition of ‘main’ was here
hello123.c:27:6: error: redefinition of ‘main’
hello123.c:2:6: note: previous definition of ‘main’ was here
hello123.c:32:6: error: redefinition of ‘main’
hello123.c:2:6: note: previous definition of ‘main’ was here
sh: 1: ./hello123.out: not found
Thanks in advance.