For my CS class, the assignment is to write a simple program that acts as a client, and connects to another program running that acts as a server. Both of these programs are running on the university's Unix server.
With the handouts he's given us, one had a link that has the client program actually written on it. Since I don't want to use that and get caught for plagirism, I used it for advice, and went on my own for most of it. The problem is now, the prewritten one works when I test it but mine doesn't. They're obviously different, but mine doesn't even seem to begin, whereas the test begins and runs just fine.
Here's mine:
Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
/*#include <arpa/inet.h>
#include <string.h>
*/
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
printf("Client Started/n");
int sockFd, portnum, n;
char buffer[256];
sockFd = socket(AF_INET, SOCK_STREAM, 0);
printf("Socket Made /n");
portnum = atoi(argv[2]);
struct sockaddr_in sa;
struct hostent *hp;
hp = gethostbyname(argv[1]);
sa.sin_family = AF_INET;
sa.sin_port = htons(portnum);
memcpy(&sa.sin_addr, hp, sizeof(hp)+1);
n = connect(sockFd, (struct sockaddr *)&sa, sizeof(sa));/*Not the segfault*/
printf("Socket Connected/n");
fgets(buffer,255,stdin);/*not the segfault*/
n = write(sockFd, buffer, strlen(buffer));
n = read(sockFd, buffer, strlen(buffer));
printf("ACK: ");
printf("%s\n",buffer);
close(sockFd);
system("pkill -9 -f Server");
return 0;
}
Here's the test:
Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
printf("Client Started");
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
return 0;
}
I compile them both the same, I run them both the same, yet mine won't even show the "Client Started" output whereas the test will and then continue on. What's going on? Thanks!