I am working on socket with C, and needs to pass command line argument from the client to the server. The server then needs to switch the cases of the sting and send it back to the client. I am stuck at passing the command line argument to the server and then sending it back after switching the case. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 10291
#define MAXLINE 9999
// Client side code
int main(int argc, char *argv[])
{
int sockfd;
char buffer[MAXLINE];
char clientMsg;
struct sockaddr_in servaddr;
// Creating socket file descriptor
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
//Connect to the Server
connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
printf("Connected to the Server. \n");
int n, len;
// Getting Input From Client
/*
printf("Please Enter Your Message: ");
scanf("%s", &clientMsg);
*/
if (argc == 2)
{
for (int i = 0; argc; i++)
{
// send(sockfd, &argv[i], 10000, 0);
sendto(sockfd, (const char *) &clientMsg, strlen(&clientMsg),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
}
printf("Message sent to server. \n");
}
else
{
printf("Error: please enter the correct number of arguments. \n");
close(sockfd);
printf("Disconnected from the server. \n");
exit(1);
}
/*
// Sending message to server
sendto(sockfd, (const char *) &clientMsg, strlen(&clientMsg),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("Message sent to server. \n");
*/
// Receive message from server
n = recvfrom(sockfd, (char*) buffer, MAXLINE,
MSG_WAITALL, (struct sockaddr *) &servaddr, &len);
buffer[n] = '\0';
printf("Message Received From Server: %s\n", buffer);
//Disconnet from the Server
close(sockfd);
printf("Disconneted from the Server. \n");
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 10291
#define MAXLINE 9999
// Server Side code
int main(int argc, char *argv[])
{
int sockfd;
char buffer[MAXLINE];
struct sockaddr_in servaddr, cliaddr;
// Creating socket file descriptor
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
// Filling server information
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind the socket with the server address
if (bind(sockfd, (const struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
int len, n;
len = sizeof(cliaddr); //len is value/resuslt
n = recvfrom(sockfd, (char*) buffer, MAXLINE,
MSG_WAITALL, (struct sockaddr *) &cliaddr, &len);
buffer[n] = '\0';
char c;
while (buffer[c] != '\0')
{
char ch = buffer[c];
if (ch >= 'A' && ch <= 'Z')
buffer[c] = buffer[c] + 32;
else if (ch >= 'a' && ch <= 'z')
buffer[c] = buffer[c] - 32;
c++;
}
//Returning Encrypted String Received By Client
sendto(sockfd, (const char *) buffer, strlen(buffer),
MSG_CONFIRM, (const struct sockaddr *) &cliaddr, len);
close(sockfd);
return 0;
}
Here's my output:
!(https://i.stack.imgur.com/uz7RY.png)
!(https://i.stack.imgur.com/nuSI0.png)
Here is what it should look like:
!( https://i.stack.imgur.com/JnIFn.png)
The server must be able to respond to multiple consecutive client requests and execute until explicitly quit (^-C).
The client should process a single request and then quit on completion.
How should I make it right?
You should start from argv[1], since argv[0] is the program name, not an argument.
for (int i = 1; i < argc; i++) {
sendto(sockfd, argv[i], strlen(argv[i]),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
}
Related
I'm trying to send messages to a server, but when I connect, the server immediately fails receiving the message. It seems that the server "does not wait" for the user to type the message. The server is supposed to remain in that while loop, forever waiting for clients and printing their messages.
I have no idea what's wrong.
Server code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#define PORT 4000
#define WORD_SIZE 256
#define USER_SOCKETS 2
#define MAX_USERS 10
int receiveMessage(int socket, char message[])
{
int bytesReceived;
while (1)
{
bytesReceived = recv(socket, message, WORD_SIZE, 0);
if (bytesReceived < 0)
return -1;
if (bytesReceived == 0)
return 0;
}
}
int main(int argc, char *argv[])
{
int serverSockfd;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if ((serverSockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("Error creating the socket.\n");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(serv_addr.sin_zero), 8);
if (bind(serverSockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Error binding the socket..\n");
return -1;
}
if (listen(serverSockfd, 5) < 0)
{
printf("Error on listening.\n");
return -1;
}
int newSockfd;
while (1)
{
if (newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen) < 0)
{
printf("Error on accept a new client.\n");
continue;
}
char username[WORD_SIZE];
if (receiveMessage(newSockfd, username) < 0)
{
printf("Error receiving message.\n");
close(newSockfd);
}
printf("Message: %s\n", username);
close(newSockfd);
}
return 0;
}
Client 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>
#define PORT 4000
int main(int argc, char * argv[]) {
int sockfd, n;
struct sockaddr_in serv_addr;
struct hostent * server;
char buffer[256];
if (argc < 2) {
fprintf(stderr, "usage %s hostname\n", argv[0]);
exit(0);
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
printf("ERROR opening socket\n");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr = * ((struct in_addr * ) server -> h_addr);
bzero( & (serv_addr.sin_zero), 8);
if (connect(sockfd, (struct sockaddr * ) & serv_addr, sizeof(serv_addr)) < 0)
printf("ERROR connecting\n");
printf("Enter the message: ");
bzero(buffer, 256);
fgets(buffer, 256, stdin);
/* write in the socket */
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
printf("ERROR writing to socket\n");
bzero(buffer, 256);
printf("%s\n", buffer);
close(sockfd);
return 0;
}
The line:
if (newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen) < 0)
will set newSockfd to 0 if accept() succeeds, rather than to the descriptor of the socket. This is because < has a higher precedence than =, so the compiler behaves as-if you had written this:
if (newSockfd = (accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen) < 0))
You need to write this instead:
if ((newSockfd = accept(serverSockfd, (struct sockaddr *)&cli_addr, &clilen)) < 0)
I've been fiddling with this for a bit now. I have a server with a static IP address and a client sitting behind a consumer grade NAT (read a router provided by my ISP).
I'm trying to send a message, using UDP to the server and then receiving a response on the same socket. I have tried in a variety of languages, but just for the sake of it, here is my C version. I'm not sure if this a code problem or a machine configuration.
The message to the server goes through just fine, but the client never receives the response.
Client:
// Client side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from client";
struct sockaddr_in servaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
// servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_addr.s_addr = inet_addr("87.118.127.66");
int n, len;
sendto(sockfd, (const char *)hello, strlen(hello),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("Hello message sent.\n");
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, (struct sockaddr *) &servaddr,
&len);
buffer[n] = '\0';
printf("Server : %s\n", buffer);
close(sockfd);
return 0;
}
Server:
// Server side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from server";
struct sockaddr_in servaddr, cliaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
// Filling server information
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind the socket with the server address
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
sizeof(servaddr)) < 0 )
{
perror("bind failed");
exit(EXIT_FAILURE);
}
int len, n;
len = sizeof(cliaddr); //len is value/resuslt
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, ( struct sockaddr *) &cliaddr,
&len);
buffer[n] = '\0';
printf("Client : %s\n", buffer);
sendto(sockfd, (const char *)hello, strlen(hello),
MSG_CONFIRM, (const struct sockaddr *) &cliaddr,
len);
printf("Hello message sent.\n");
return 0;
}
UDP is a transport protocol and transport protocols carry a port. As you are working on this layer, the port has to be known/specified. But that is just not the case for recvfrom in your client code. It does not know from which port it should return the messages. Therefore you have to call bind and or connect in your client code.
I am trying to write a TCP socket server for a client then i ran into some problems. The server is not sending/receiving data. However, it can listen to and accept new clients.
I have tried "nc 127.0.0.1 -l 10001" to test the client and it works well. The server at one time could send and receive but encoded characters. I made some modifications and since then i have been seeing errors.
The exit Message can be commented or remove as it was declared in custom.h.
Any idea will be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "custom.h"
#define PORT 10001
#define MAXIMUM_CONNECTION 20
#define DATA_SIZE 100
int main()
{
int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in serverAddr, clientAddr;
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
exitMessage("Failed to address to port");
}
if(listen(sock, MAXIMUM_CONNECTION) < 0) {
exitMessage("Server is deaf could not listen to incoming messages");
}
char buffer[DATA_SIZE], data[DATA_SIZE];
while(1) {
memset(buffer, '\0', DATA_SIZE);
memset(data, '\0', DATA_SIZE);
socklen_t clientAddrSize = sizeof(clientAddr);
if(accept(sock, (struct sockaddr *) &clientAddr, &clientAddrSize) < 0) {
exitMessage("Could not accept new connections");
}
if(recv(sock, buffer, DATA_SIZE - 1, 0) < 0) {
exitMessage("Failed to receive data from client");
}
printf("\nReceived: \'%s\' to client\n", buffer);
printf("input data for client: ");
int index = 0;
while((data[index++] = getchar()) != '\n');
if(send(sock, data, strlen(data), 0) < 0) {
exitMessage("Failed sending to client");
}
}
}
The socket you listen on is only for accepting new connections, not reading/writing data. The accept function returns a file descriptor for the accepted socket. That is the one you should be calling recv and send on.
int newsock;
if((newsock = accept(sock, (struct sockaddr *) &clientAddr, &clientAddrSize)) < 0) {
exitMessage("Could not accept new connections");
}
if(recv(newsock, buffer, DATA_SIZE - 1, 0) < 0) {
exitMessage("Failed to receive data from client");
}
printf("\nReceived: \'%s\' to client\n", buffer);
printf("input data for client: ");
int index = 0;
while((data[index++] = getchar()) != '\n');
if(send(newsock, data, strlen(data), 0) < 0) {
exitMessage("Failed sending to client");
}
I'm trying to complete a simple echo server. The goal is to repeat back the message to the client. The server and client both compile. The server runs, you just need to give it a port to run on. The client has the address, the port, and the message. When the client goes through the program to the sendto section, it stop and waits there. My goal it to have it sent to the server, and the server to send it back.
I believe that the server works, or it least is in the mode to receive as it enters the while loops to do that. That part can send notes back that it works.
For the client, I've tried sending the argument directly, but also through a c-string. I've tried one hard coded in, and none of them have worked. I've been at it for many hours, so I decided to ask for help because I can't think of anything else as a newbie.
Client
//argv[1] address, argv[2] port, argv[3] message
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
int main(int argc, char *argv[]){
int BUF_LEN;
for (BUF_LEN = 0; argv[3][BUF_LEN] != '\0'; BUF_LEN++){
// printf("BUF_LEN = %i\n", BUF_LEN);
}
int s, n, port_no, r;
struct sockaddr_in server_addr;
char *haddr, *message;
char buf[BUF_LEN+1];
printf("Variables created\n");
s = socket(AF_INET, SOCK_DGRAM, 0); // create a socket for UDP
printf("Socket created as s: %i\n", s);
bzero((char *)&server_addr, sizeof(server_addr)); // clear
server_addr.sin_family = AF_INET; //IPv4 Internet family
server_addr.sin_addr.s_addr = inet_addr(argv[1]); //server address
server_addr.sin_port = htons(atoi(argv[2])); // server port number
printf("Server addr complete\n");
//Bind() - Not necessary
printf("Bind skipped\n");
//sendto()
r = sendto(s, argv[3], strlen(argv[3]), 0, (struct sockaddr *)&server_addr, BUF_LEN);
printf("Message Sent");
//recvfrom()
n = recvfrom (s, buf, BUF_LEN, 0, (struct sockaddr *)&server_addr, &BUF_LEN);
printf("Message Received: %s\n", buf);
close(s);
}
Server
//Argv[1] : port number
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char *argv[]){
int n;
int MAXLINE = 512;
int sock_server, sock_client, r, len;
char buf[MAXLINE];
struct sockaddr_in my_addr, client_addr;
//printf("Variables created\n");
sock_server = socket (PF_INET, SOCK_DGRAM, 0);
//printf("Socket created\n");
if (sock_server < 0){
perror("Bind failed");
exit(1);
}
bzero(&my_addr, sizeof(my_addr)); // clear
my_addr.sin_family = AF_INET; //Address Family INET
my_addr.sin_port = htons(atoi(argv[1])); //Server port number
my_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Accept from anywhere
//printf("Addresses created\n");
r = bind(sock_server, (struct sockaddr*)(&my_addr), sizeof(my_addr));
if (r < 0) {
perror("Bind failed");
exit(1);
}
printf("Read to receive\n");
while(1) {
//printf("First while loop\n");
len = sizeof(struct sockaddr_in);
//recvfrom()
n = recvfrom (sock_client, buf, MAXLINE, 0, (struct sockaddr *)&client_addr, &len);
while (n > 1){
printf("Second while loop\n");
printf("Message Received: %s\n", buf);
//sendto()
sendto(sock_client, buf, n, 0, (struct sockaddr *)&client_addr, len);
n = 0;
}
}
close(sock_client); //close the client socket
//printf("Connection sock_client Closed");
}
Here is the fixed version of the client using sizeof(server_addr) in the client call of sendto:
//argv[1] address, argv[2] port, argv[3] message
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
int main(int argc, char *argv[]){
int BUF_LEN;
for (BUF_LEN = 0; argv[3][BUF_LEN] != '\0'; BUF_LEN++){
// printf("BUF_LEN = %i\n", BUF_LEN);
}
int s, n, port_no, r;
struct sockaddr_in server_addr;
char *haddr, *message;
char buf[BUF_LEN+1];
printf("Variables created\n");
s = socket(AF_INET, SOCK_DGRAM, 0); // create a socket for UDP
printf("Socket created as s: %i\n", s);
bzero((char *)&server_addr, sizeof(server_addr)); // clear
server_addr.sin_family = AF_INET; //IPv4 Internet family
server_addr.sin_addr.s_addr = inet_addr(argv[1]); //server address
server_addr.sin_port = htons(atoi(argv[2])); // server port number
printf("Server addr complete\n");
//Bind() - Not necessary
printf("Bind skipped\n");
r = sendto(s, argv[3], strlen(argv[3]), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
printf("Message Sent");
n = recvfrom (s, buf, BUF_LEN, 0, (struct sockaddr *)&server_addr, &BUF_LEN);
printf("Message Received: %s\n", buf);
close(s);
}
I posted my code here: communication between windows client and linux server?
I am performing communication between client and server.I know that udp is a connectionless program nothing but it wont send any response back to the client. If i want to send a response back to the client then what should i do ??
I solved all my errors in the above link but I got a doubt w.r.t sending a response back to the client. so i am re posting here.
This is the code I wrote when I start learning socket programming, hope it helps:
server
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
struct sockaddr_in server;
struct sockaddr_in client;
int socket_fd;
int ret;
char buf[255];
int len = sizeof(struct sockaddr_in);
socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(socket_fd < 0)
{
printf("socket error\n");
return -1;
}
server.sin_family = AF_INET;
server.sin_port = htons(5900);
server.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(socket_fd, (struct sockaddr *)&server, sizeof(struct sockaddr));
if(ret)
{
printf("error while binding\n");
return -1;
}
ret = recvfrom(socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&client, &len);
if(ret < 0)
{
printf("reciving error\n");
}
printf("recving data from %s: %s\n", inet_ntoa(client.sin_addr), buf);
snprintf(buf, sizeof(buf), "server:");
ret = sendto(socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&client, sizeof(client));
if(ret < 0)
{
printf("send error\n");
return -1;
}
close(socket_fd);
return 0;
}
client
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int socket_fd;
struct sockaddr_in server;
int ret;
char buf[255] = "send to server";
int len = sizeof(struct sockaddr_in);
socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(socket_fd < 0)
{
printf("socket error\n");
}
server.sin_family = AF_INET;
server.sin_port = htons(5900);
server.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = sendto(socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&server, sizeof(server));
if(ret < 0)
{
printf("sendto error\n");
return -1;
}
ret = recvfrom(socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&server, &len);
if(ret < 0)
{
printf("error recv from\n");
return -1;
}
printf("recving from server:%s: %s\n", inet_ntoa(server.sin_addr), buf);
close(socket_fd);
}
Read the code above and you will find the answer to your question