This is my C client code. Somehow it is not working. It worked when I tried with argument passing.
I want the program to ask user to give hostname
then it will ask for portname
and then the message to send:
Enter hostname: localhost
Enter portname: 56456
Enter message : Hi user
Enter message : What's up
Enter message : How are you
And once the host and port given it should not ask for again (until restart the program). I tried with do while
loop, but it is not working.
On server it will display the sent message
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
//int main(int argc, char *argv[])
int main()
{
char *argv[256];
int argc;
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
printf("\n\nEnter Hostname\n\n");
fgets(argv[0],256,stdin);
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);
//buffer = tempFunc();
fgets(buffer,255,stdin);
printf("\n\nHere Goes the output\n%s",buffer);
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);
close(sockfd);
return 0;
}