I'm trying to get the HTML of this page http://pastebin.com/raw/7y7MWssc using C. So far I'm trying to connect to pastebin using sockets & port 80, and then use a HTTP request to get the HTML on that pastebin page.
I know what I have so far is probably WAY off, but here it is:
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main()
{
/*Define socket variables */
char host[1024] = "pastebin.com";
char url[1024] = "/raw/7y7MWssc";
char request[2000];
struct hostent *server;
struct sockaddr_in serverAddr;
int portno = 80;
printf("Trying to get source of pastebin.com/raw/7y7MWssc ...\n");
/* Create socket */
int tcpSocket = socket(AF_INET, SOCK_STREAM, 0);
if(tcpSocket < 0) {
printf("ERROR opening socket\n");
} else {
printf("Socket opened successfully.\n");
}
server = gethostbyname(host);
serverAddr.sin_port = htons(portno);
if(connect(tcpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
printf("Can't connect\n");
} else {
printf("Connected successfully\n");
}
bzero(request, 2000);
sprintf(request, "Get %s HTTP/1.1\r\n Host: %s\r\n \r\n \r\n", url, host);
printf("\n%s", request);
if(send(tcpSocket, request, strlen(request), 0) < 0) {
printf("Error with send()");
} else {
printf("Successfully sent html fetch request");
}
printf("test\n");
}
The code above made sense to a certain point, and now I'm confused. How would I make this get the web source from http://pastebin.com/raw/7y7MWssc ?
Fixed, i needed to set add
serverAddr.sin_family = AF_INET;
and bzero serverAddr, and also my HTTP request was wrong, it had an extra /r/n and spaces, like #immibis said.
Corrected:
sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", url, host);
You are getting the pointer returned by gethostbyname() but you weren't doing anything with it.
You need to populate the sockaddr_in with the address, domain and port.
This works...but now you need to worry about obtaining the response...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main()
{
/*Define socket variables */
char host[1024] = "pastebin.com";
char url[1024] = "/raw/7y7MWssc";
char request[2000];
struct hostent *server;
struct sockaddr_in serverAddr;
short portno = 80;
printf("Trying to get source of pastebin.com/raw/7y7MWssc ...\n");
/* Create socket */
int tcpSocket = socket(AF_INET, SOCK_STREAM, 0);
if(tcpSocket < 0) {
printf("ERROR opening socket\n");
exit(-1);
} else {
printf("Socket opened successfully.\n");
}
if ((server = gethostbyname(host)) == NULL) {
fprintf(stderr, "gethostbybname(): error");
exit(-1);
}
memcpy(&serverAddr.sin_addr, server -> h_addr_list[0], server -> h_length);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(portno);
if(connect(tcpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
printf("Can't connect\n");
exit(-1);
} else {
printf("Connected successfully\n");
}
bzero(request, 2000);
sprintf(request, "Get %s HTTP/1.1\r\n Host: %s\r\n \r\n \r\n", url, host);
printf("\n%s", request);
if(send(tcpSocket, request, strlen(request), 0) < 0) {
printf("Error with send()");
} else {
printf("Successfully sent html fetch request");
}
printf("test\n");
}
Related
I have a piece of C code that should connect to www.google.com and make a HTTP GET request, but when I run it, it stays on "Connecting.." for about 30 seconds before returning "Connection Failed" and an exit return value of 255. What am I doing wrong?
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define PORT 8000
struct hostent *hostinfo;
int main(void) {
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hostname = "www.google.com";
char *request = "GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n";
hostinfo = gethostbyname(hostname);
char *ip = inet_ntoa(*(struct in_addr*)hostinfo->h_addr_list[0]);
char buffer[1024] = {0};
printf("Creating socket...\n");
if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
printf("Checking address...\n");
if(inet_pton(AF_INET, ip, &serv_addr.sin_addr) <= 0){
printf("\n Invalid IP/Address not supported \n");
return -1;
}
printf("Connecting to host %s...\n", ip);
if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
printf("\n Connection Failed \n");
return -1;
}
send(sock, request, strlen(request), 0);
printf("Message sent\n");
valread = read(sock, buffer, 1024);
printf("%s\n", buffer);
return 0;
}
I see two major problems.
You use the wrong port. Use port 80 for http.
Your read and printf is a dangerous combination that could easily cause access out of bounds (and undefined behavior). What you read from the socket will not be null terminated. You could instead do something like this:
...
printf("Message sent\n");
while((valread = read(sock, buffer, sizeof(buffer))) > 0) {
fwrite(buffer, valread, 1, stdout);
}
This will however block when everything has been read. See non-blocking I/O or consider using select, epoll or poll to wait for available data on sockets.
If you are only interested in getting the response and then disconnect, you could however use Connection: close to close the connection after the server has sent the response. Full code below:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define PORT 80
int main(void) {
int sock = 0, valread;
struct hostent *hostinfo;
struct sockaddr_in serv_addr;
const char *hostname = "www.google.com";
const char *request = "GET / HTTP/1.1\r\n"
"Host: www.google.com\r\n"
"Connection: close\r\n\r\n"; // <- added
hostinfo = gethostbyname(hostname);
char *ip = inet_ntoa(*(struct in_addr*)hostinfo->h_addr_list[0]);
char buffer[1024] = {0};
printf("Creating socket...\n");
if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
printf("Checking address...\n");
if(inet_pton(AF_INET, ip, &serv_addr.sin_addr) <= 0){
printf("\n Invalid IP/Address not supported \n");
return -1;
}
printf("Connecting to host %s...\n", ip);
if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
perror("connect()");
return -1;
}
send(sock, request, strlen(request), 0);
printf("Message sent\n");
while((valread = read(sock, buffer, sizeof(buffer))) > 0) {
fwrite(buffer, valread, 1, stdout);
}
}
I have been looking everywhere for an answer. I am new to coding in C and would have loved it if my Professor would have allowed us to choose the language, but I digress. I am running Oracle V-Box locally running Ubuntu client and a Ubuntu server. I compile the code below on both the server and the client, with a few warnings. I run the code on the server (seems fine) and then on the client. The client is asking to send over a PDF file just like I did with the TCP socket transfer (which worked great). I also have Wireshark running on the client and server, and it looks like the request is sent out from the client but the server doesn't do anything and just sits on both ends without pulling the file over. Not sure if it is the code or something else.
/* Echo server using UDP */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERVER_UDP_PORT 2466
#define MAXLEN 4096
int main(int argc, char **argv)
{
int sd, client_len, port, n;
char buf[MAXLEN];
struct sockaddr_in server, client;
switch(argc) {
case 1:
port = SERVER_UDP_PORT;
break;
case 2:
port = atoi(argv[1]);
break;
default:
fprintf(stderr, "Usage: %s [port]\n", argv[0]);
exit(1);
}
/* Create a datagram socket */
if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
fprintf(stderr, "Can't create a socket\n");
exit(1);
}
/* Bind an address to the socket */
bzero((char *)&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sd, (struct sockaddr *)&server,
sizeof(server)) == -1) {
fprintf(stderr, "Can't bind name to socket\n");
exit(1);
}
while (1) {
client_len = sizeof(client);
if ((n = recvfrom(sd, buf, MAXLEN, 0,
(struct sockaddr *)&client, &client_len)) < 0) {
fprintf(stderr, "Can't receive datagram\n");
exit(1);
}
if (sendto(sd, buf, n, 0,
(struct sockaddr *)&client, client_len) != n) {
fprintf(stderr, "Can't send datagram\n");
exit(1);
}
}
close(sd);
return(0);
}
This is the client code
// UDP Echo Client
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERVER_UDP_PORT 2466
#define MAXLEN 4096
#define DEFLEN 64
long delay(struct timeval t1, struct timeval t2)
{
long d;
d = (t2.tv_sec - t1.tv_sec) * 1000;
d += ((t2.tv_usec - t1.tv_usec + 500) / 1000);
return(d);
}
int main(int argc, char **argv)
{
int data_size = DEFLEN, port = SERVER_UDP_PORT;
int i, j, sd, server_len;
char *pname, *host, rbuf[MAXLEN], sbuf[MAXLEN];
struct hostent *hp;
struct sockaddr_in server;
struct timeval start, end;
unsigned long address;
pname = argv[0];
argc--;
argv++;
if (argc > 0 && (strcmp(*argv, "-s") == 0)) {
if (--argc > 0 && (data_size = atoi(*++argv))) {
argc--;
argv++;
}
else {
fprintf(stderr,
"Usage: %s [-s data_size] host [port]\n", pname);
exit(1);
}
}
if (argc > 0) {
host = *argv;
if (--argc > 0)
port = atoi(*++argv);
}
else {
fprintf(stderr,
"Usage: %s [-s data_size] host [port]\n", pname);
exit(1);
}
if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
fprintf(stderr, "Can't create a socket\n");
exit(1);
}
bzero((char *)&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(port);
if ((hp = gethostbyname(host)) == NULL) {
fprintf(stderr, "Can't get server's IP address\n");
exit(1);
}
bcopy(hp->h_addr, (char *) &server.sin_addr, hp->h_length);
if (data_size > MAXLEN) {
fprintf(stderr, "Data is too big\n");
exit(1);
}
for (i = 0; i < data_size; i++) {
j = (i < 26) ? i : i % 26;
sbuf[i] = 'a' + j;
} // construct data to send to the server
gettimeofday(&start, NULL); /* start delay measurement */
server_len = sizeof(server);
if (sendto(sd, sbuf, data_size, 0, (struct sockaddr *)
&server, server_len) == -1) {
fprintf(stderr, "sendto error\n");
exit(1);
}
if (recvfrom(sd, rbuf, MAXLEN, 0, (struct sockaddr *)
&server, &server_len) < 0) {
fprintf(stderr, "recvfrom error\n");
exit(1);
}
gettimeofday(&end, NULL); /* end delay measurement */
if (strncmp(sbuf, rbuf, data_size) != 0)
printf("Data is corrupted\n");
close(sd);
return(0);
}
Once I compile I run the code on Server normally:
./udp_server
and just sits waiting from the client.
Once I compile I run the code on Client:
./udp_client -s 1500 10.0.2.11 2466 > test.pdf
I run this which is (./udp_client -s data_rate server_IP Server_Port > (output to file on desktop of client))
This just produces a blank page. It should have a few pages of text and pics.
I also am getting the send out from client on Wireshark but no reply from server.
This is what i am getting when i run STRACE from terminal
strace ./udp_server
I think you just forgot to print out the received data in the client:
if (strncmp(sbuf, rbuf, data_size) != 0)
printf("Data is corrupted\n");
close(sd);
printf(rbuf); // <----
return(0);
Your client code currently only prints out error messages. If everything works, it won't produce any output.
Hi, I am developing Server client between two different operating
systems. I am executing server on Ubuntu 14.04 & Client on Windows.
/* Simple Server code on TCP/IP protocol */
#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 length 512
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno; //Declare variable for Socket and port
socklen_t clilen; //Client address and port no
char buffer[length]; //Buffer for message
struct sockaddr_in serv_addr, cli_addr; //Srtructure for server and Client address
int n; //Check whether listen,accept,read,write process done
FILE *fileptr; //File pointer
int datasize;
/* Check Portno. provided or not */
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
/*Create socket*/
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr)); //Clear memory for Server address
portno = atoi(argv[1]); //Convert portno in to Integer from ASCII
/*Server address and all other details */
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
/*Bind socket*/
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
/*Listening to socket and waiting for users(max.5) */
listen(sockfd,5);
clilen = sizeof(cli_addr); //Size of Client address
/*Accept users*/
newsockfd= accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);
if (newsockfd< 0)
error("ERROR on accept");
/*File operations */
char* fs_name = "/home/ankur/Desktop/RTSIM_Dump.csv";
fileptr=fopen(fs_name,"r"); //Open file
/*Write and Read operation to socket*/
bzero(buffer,length);
while((datasize = fread(buffer,sizeof(char),length,fileptr))>0)
{
if(send(newsockfd,buffer,datasize,0)<0)
{
fprintf(stderr, "ERROR: Failed to send file :%s (errno = %d)\n",fs_name,errno);
break;
}
bzero(buffer,length);
}
fclose(fileptr); //Close file
close(newsockfd); //Close to accept client
close(sockfd); //close socket
return 0;
}
//Client code:
------------------------------------------------------------------------------#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "2222"
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char sendbuf[DEFAULT_BUFLEN];
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen;
FILE *fileptr;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
//Receive file from Server and save it.
fileptr = fopen("/Desktop/RTSIM_Dump.csv","w");
if (fileptr == NULL)
{
printf("ERROR:Create/Open file");
exit(1);
}
int write_sz;
memset(recvbuf,0,DEFAULT_BUFLEN);
while((recvbuflen = recv(ConnectSocket,recvbuf,DEFAULT_BUFLEN,0))>0)
{
write_sz = fwrite(recvbuf,sizeof(char),recvbuflen,fileptr);
if(write_sz < recvbuflen)
{
printf("File write failed.\n");
}
memset(recvbuf,0,DEFAULT_BUFLEN);
if(recvbuflen == 0 || recvbuflen != 512)
{
break;
}
}
if(recvbuflen < 0)
{
printf("recv() timed out.\n");
}
// cleanup
fclose(fileptr);
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
------------------------------------------------------------------------------ I am getting errno 104 on server (Ubuntu) & create/open file error on
Windows.
Thanks in advance!!!
I checked server client on Ubuntu , it works perfectly but when i
tried it with Windows client. It gives me error during execution.
fileptr = fopen("/Desktop/RTSIM_Dump.csv","w");
That is incorrect path for windows. More proper would be "\Desktop\RTSIM_Dump.csv". Note that the directories in the path must exist and have appropriate permissions.
Where do you get error 104 in server?
I'm writing 2 small test programs in C (client/server) and I'm having trouble sending messages from the server to the client (but the other way around works just fine). The server says it sent 20 bytes, but on the client's end it says "failed to receive data". I would appreciate any help, thank you so much! My code is below:
Server:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netinet/in.h>
int main(int argc, char* argv[])
{
int sockfd, client_sockfd;
struct sockaddr_in server;
int reading, fileSize;
int i; //counter
int bytesSent;
char test[20] = "test message\n";
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[1])); //assign port to listen to
server.sin_addr.s_addr = INADDR_ANY; //IP address
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) //create socket failed
{
perror("socket");
exit(1);
}
if(bind(sockfd, (struct sockaddr *) &server, sizeof(server)) == -1) //connect server socket to specified port
{
perror("bind call failed");
exit(1);
}
//printf("listening to port %d\n", server.sin_port);
if(listen(sockfd, 5) == -1) //queue size of 5
{
perror("listen call failed");
exit(1);
}
while(1) //infinite loop to process connections from clients
{
client_sockfd = accept(sockfd, NULL, NULL); //accept anything
if(client_sockfd == -1)
perror("accept call failed");
bytesSent = send(client_sockfd, test, 20, 0);
printf("bytes sent: %d\n", bytesSent);
}
close(client_sockfd);
close(sockfd);
return 0;
}
Client:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char* argv[])
{
int sockfd;
struct sockaddr_in server;
struct hostent *server_ip_address;
server_ip_address = gethostbyname("eos-class.engr.oregonstate.edu");
int sent; //number of bytes sent
int received; //number of bytes received
char passedMsg[20]; //holds received message
if(server_ip_address == NULL)
{
fprintf(stderr, "could not resolve server host name\n");
exit(1);
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[3])); //assign port to connect to
memcpy(&server.sin_addr, server_ip_address->h_addr, server_ip_address->h_length);
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) //create socket failed
{
perror("socket");
exit(1);
}
if(connect(sockfd, (struct sockaddr *) &server, sizeof(server)) == -1) //connect socket to remote address failed
{
printf("tried to connect to port %d\n", server.sin_port);
perror("connect");
exit(1);
}
if((received = recv(sockfd, passedMsg, 20, 0)) < 0);
{
printf("Failed to receive data\n");
exit(1);
}
printf("Received message: %s\n", passedMsg);
close(sockfd);
return 0;
}
In your client code, in the error checking for recv, change printf to perror. If you do, the output will be:
Failed to receive data: Success
So the recv call was successful, but the error code ran anyway. Why? Let's take a closer look at that if statement:
// what's this? ----v
if((received = recv(sockfd, passedMsg, 20, 0)) < 0);
{
printf("Failed to receive data\n");
exit(1);
}
There's a stray ; after the condition in the if statement. This means that the if statement does nothing if the condition is true, and that the following block is not the body of the if but an independent block that always runs.
Get rid of the extra ; and you get the expected results.
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.
In this hello.c / hello123.c, I am trying to connect back to the same client.
/* 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");
fclose(fr);
}
system("gcc hello123.c -o hello123.out");
system("./hello123.out");
}
}
The following is the Client Program.
/* 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 PORT1 20001
#define PORT2 20002
#define LENGTH 512
int main(int argc, char *argv[]){
int sockfd;
int nsockfd;
char revbuf[LENGTH];
struct sockaddr_in remote_addr;
struct sockaddr_in server;
struct sockaddr_in dest;
int status,socket_fd, client_fd,num;
socklen_t size;
char buffer[1024];
char *buff, ch;
/* 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(PORT1);
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", PORT1);
/* 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);
//}
//while(1) {
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(PORT2);
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr);
bzero(&(remote_addr.sin_zero), 8);
size = sizeof(struct sockaddr_in);
if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 )
{
perror("accept");
exit(1);
}
printf("Server got connection from client %s\n", inet_ntoa(dest.sin_addr));
while(1) {
if ((num = recv(client_fd, buffer, 1024,0))== -1) {
perror("recv");
exit(1);
}
else if (num == 0) {
printf("Connection closed\n");
//So I can now wait for another client
break;
}
buffer[num] = '\0';
printf("Server:Msg Received %s\n", buffer);
}//End of Inner While...
//Close Connection Socket
close(client_fd);
close (sockfd);
printf("[Client] Connection lost.\n");
return (0);
}
The following is the Hello.c
/* Hello.c */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 20002
#define MAXSIZE 1024
#define SA struct sockaddr
int main(int argc, char *argv[])
{
int sockfd,connfd;
struct sockaddr_in server_info;
struct hostent *he;
int socket_fd,client_fd,num;
char buffer[1024];
char i;
char buff[1024];
struct sockaddr_in servaddr,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
printf("Hello:socket creation failed...\n");
exit(0);
}
else
printf("Hello:Socket successfully created..\n");
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port=htons(PORT);
if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))!=0)
{
printf("Hello:connection with the server failed...\n");
exit(0);
}
else
printf("Hello:connected to the server..\n");
printf("\n Hello:Choose between 1 and 2\n");
printf("Hello:Enter Data for Server:\n");
fgets(buffer,MAXSIZE,stdin);
if ((send(socket_fd,buffer, strlen(buffer),0))== -1) {
fprintf(stderr, "Hello:Failure Sending Message\n");
close(socket_fd);
exit(1);
}
else {
printf("Hello:Client:Message being sent: %c\n",i);
close(socket_fd);
}
}
When I run the program, the file transfer is happening successfully. But the Hello.c is not getting connected to the client.
This is my output
Server Side:
$ ./server24.out
[Server] Obtaining socket descriptor successfully.
[Server] Binded tcp port 20001 in addr 127.0.0.1 sucessfully.
[Server] Listening the port 20001 successfully.
[Server] Server has got connected from 127.0.0.1.
msg:
Ok received from client!
Hello:Socket successfully created..
Hello:connection with the server failed...
Client Side:
$ ./client24.out
[Client] Connected to server at port 20001...ok!
[Client] Sending hello.c to the Server. Ok File hello.c from Client was Sent
accept: Socket operation on non-socket
I guess this is some address problem. But I am not able to figure out.
Please help.
Thanks in advance.
So your Client Program begin to act as a server but you haven't created the necessary socket to accept a connection there. socket_fd have been used uninitialized from socket()
Following need to be added updated after //while(1) { in Client
//while(1) {
/* Get the Socket file descriptor */
if ((socket_fd= 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(PORT2);
inet_pton(AF_INET, "127.0.0.1", &remote_addr.sin_addr);
bzero(&(remote_addr.sin_zero), 8);
if ((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 )
{
perror("accept");
exit(1);
}