Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#define BUFMAX 4096
int sendData(int sockfd);
int recvData(int sockfd);
main(int argc, char *argv[])
{
int listenfd, connfd, port;
pid_t childpid;
size_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if (argc != 2) {
printf("USAGE: tcpserv <port>\n");
exit(1);
}
port = (int)&argv[1];
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
perror("socket");
memset(&serv_addr, '\0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(INADDR_ANY);
serv_addr.sin_port = htons(port);
if (bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == -1)
perror("bind");
if (listen(listenfd, 5) == -1)
perror("listen");
else
printf("Listening for connection request on port %d...\n",port);
for (;;) {
clilen = sizeof(cli_addr);
if ((connfd = accept(listenfd, (struct sockaddr *) &cli_addr, &clilen)) == -1)
perror("accpet");
if ( (childpid = fork() ) == 0) { /* creates child process */
close(listenfd);
int choice = 0;
while (choice == 0) {
printf("\n1. Send Data\n");
printf("2. Receive Data\n");
printf("3. Quit\n\n");
scanf("%d", choice);
if (choice == 1)
if (sendData(connfd) != 0)
printf("Error occured in sendData\n");
else if (choice == 2)
if (recvData(connfd) != 0)
printf("Error occured in recvData\n");
else if (choice == 3) {
close(connfd);
exit(1);
}
else
printf("Invalid choice, choose again.\n");
choice = 0;
}
exit(0);
}
}
}
int sendData(int sockfd)
{
char file[20], *buffer[BUFMAX];
size_t bytes_read, bytes_sent, filesz;
FILE *pFile = NULL;
printf("Enter name of file to send.\n\n");
scanf("%s",&file);
pFile = fopen(file,"r");
filesz = sizeof(pFile);
if ((bytes_read = fread(buffer,1,filesz,pFile)) < 1)
perror("fread");
if ((bytes_sent = send(sockfd, buffer, bytes_read, 0)) == -1)
perror("send");
else if (bytes_sent < bytes_read) {
printf("\nError sending file!\n");
return -1;
}
else {
printf("\nFile sent!\n");
return 0;
}
fclose(pFile);
}
int recvData(int sockfd)
{
char *buffer[BUFMAX], *file;
size_t bytes_recv, bytes_svd;
FILE *pFile;
if ((bytes_recv = recv(sockfd, buffer, sizeof(buffer),0)) == -1) {
perror("recv");
exit(0);
}
printf("\nWhat would you like to save the file as?\n");
scanf("%s",file);
pFile = fopen(file,"w+b");
if ((bytes_svd = fwrite(buffer,1,sizeof(buffer),pFile)) == -1) {
perror("fwrite");
return -1;
}
else if (bytes_svd < bytes_recv) {
printf("Only partial file saved!\n");
fclose(pFile);
exit(0);
}
printf("\nFile saved to disk!\n");
fclose(pFile);
return 0;
}
hope its not something too embarassing, thanks in advance for any ideas.
edit: i just noticed i didnt include string.h, but thats still not the problem. Also, that in the choice menu i had 'choice' instead of '&choice', yet i am still getting the seg fault.