I have an odd issue. I have been attempting to learn to use network sockets in C/C++, and I'm currently having trouble understanding why my server code does not work. I have followed a tutorial's code almost to a T, and although the example code functions fine, my code does not. I can telnet localhost 5000 to the example program just fine, but telnet simply gives me connection refused when I test my server code.
Here is my code:
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main()
{
// declare int socket descriptor and call socket() to assign to it
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
perror("Error on socket creation.");
// declare address struct
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof serv_addr);
// set values in address struct
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
// need to cast sockaddr_in to sockaddr struct
bind(sockfd, (struct sockaddr*)&serv_addr, sizeof serv_addr);
// listen on socket with num of allowed connections
if (listen(sockfd, 10) == -1)
perror("Error on listen");
int connfd;
char msg [1025];
memset(msg, 0, sizeof msg);
while (1)
{
connfd = accept(sockfd, (struct sockaddr*)NULL, NULL);
strcpy(msg, "Message lol");
write(connfd, msg, strlen(msg));
close(connfd);
sleep(1);
}
return 0;
}
This is example that functions as expected: https://pastebin.com/CG9ZWz49
And this is the tutorial I got the example from:
https://www.codeproject.com/articles/586000/networking-and-socket-programming-tutorial-in-c
Any help would be greatly appreciated. Thanks.
Related
Im just trying to figure out my error, yes I have tried googling it. Any help would be appreciated. I am just trying to make a C++ program of a server and a client that communicate with each other using UDP.
#include <iostream>
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include "m-c2.h"
#define PORT 8080
#define MAXLINE 1000
int main()
{
char buffer[100];
char *message = "Hello Client";
int listenfd, len;
struct sockaddr_in servaddr, cliaddr;
bzero(&servaddr, sizeof(servaddr));
// Create a UDP Socket
listenfd = socket(AF_INET, SOCK_DGRAM, 0);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
// bind server address to socket descriptor
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
//receive the datagram
len = sizeof(cliaddr);
int n = recvfrom(listenfd, buffer, sizeof(buffer),
0, (struct sockaddr*)&cliaddr,&len); //receive message from server
buffer[n] = '\0';
puts(buffer);
// send the response
sendto(listenfd, message, MAXLINE, 0,
(struct sockaddr*)&cliaddr, sizeof(cliaddr));
}
I tried googling, and that didn't help.
The last parameter of recvfrom() expects a pointer to a socklen_t, but you are passing it a pointer to an int instead. They are not the same type.
You just need to fix your declaration of len accordingly, eg change this:
int listenfd, len;
To this instead:
int listenfd;
socklen_t len; // <--
i am trying to implement a TCP server that accepts multiple client nodes. However, the control is just stuck at select() and not moving beyond that. This is my code:
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(){
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(2987);
inet_pton(AF_INET, "0.0.0.0", &hint.sin_addr);
bind(server_socket, (sockaddr*)&hint, sizeof(hint));
listen(server_socket, SOMAXCONN);
fd_set master;
FD_ZERO(&master);
FD_SET(server_socket, &master);
int client_socket;
sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
while(true){
fd_set copy = master;
int socket_count = select(0, ©, nullptr, nullptr, nullptr);
cout << "Reached here!" << endl;
for(int i=0; i<socket_count; i++){
if(FD_ISSET(i, ©)){
if(i == server_socket){
client_socket = accept(server_socket, (sockaddr *) &client_addr, &client_len);
}else{
// Message
}
}
}
}
}
However, the control never moves beyond the select statement. It just remain there even after i open a connection to the server with telnet:
$ telnet 127.0.0.1 2987
Why it stuck there and how do i get the client socket with this?
Here is the manual of select.
The first parameter should not be zero, but be the highest file-descriptor that select should manage plus 1. In your case it's:
int socket_count = select(server_socket + 1, ©, nullptr, nullptr, nullptr);
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 is binded to localhost and port 8080. 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.
Problem: The client is send the message and the server is receiving it correctly but the server is not able to return the message. Please help!
SERVER SIDE CODE:
#include <iostream>
#include <string.h>
#include <fstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
using namespace std;
int main() {
int serSockDes, len, readStatus;
struct sockaddr_in serAddr, cliAddr;
char buff[1024] = {0};
char msg[] = "Hello to you too!!!\n";
//creating a new server socket
if((serSockDes = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket creation error...\n");
exit(-1);
}
//binding the port to ip and port
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons(PORT);
serAddr.sin_addr.s_addr = INADDR_ANY;
if((bind(serSockDes, (struct sockaddr*)&serAddr, sizeof(serAddr))) < 0) {
perror("binding error...\n");
exit(-1);
}
readStatus = recvfrom(serSockDes, buff, 1024, 0, (struct sockaddr*)&cliAddr, (socklen_t*)&len);
buff[readStatus] = '\0';
cout<<buff;
cout<<len;
sendto(serSockDes, msg, strlen(msg), 0, (struct sockaddr*)&cliAddr, len);
return 0;
}
CLIENT SIDE CODE:
#include <iostream>
#include <fstream>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
using namespace std;
int main(int argc, char** argv) {
int cliSockDes, readStatus, len;
struct sockaddr_in serAddr;
char msg[] = "Hello!!!\n";
char buff[1024] = {0};
//create a socket
if((cliSockDes = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket creation error...\n");
exit(-1);
}
//server socket address
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons(PORT);
serAddr.sin_addr.s_addr = INADDR_ANY;
sendto(cliSockDes, msg, strlen(msg), 0, (struct sockaddr*)&serAddr, sizeof(serAddr));
readStatus = recvfrom(cliSockDes, buff, 1024, 0, (struct sockaddr*)&serAddr, (socklen_t*)&len);
buff[readStatus] = '\0';
cout<<buff;
return 0;
}
The client is trying to send its message to INADDR_ANY, which is wrong. It needs to send to a specific IP address instead. The server can listen to all of its local IP addresses using INADDR_ANY, that is fine, but the IP address that the client sends to must be one that the server listens on (or, if the client and server are on different network segments, the client must send to an IP that reaches the server's router, which then must forward the message to an IP that the server is listening on).
Also, your calls to recvfrom() and sendto() on both ends are lacking adequate error handling. In particular, the addrlen parameter of recvfrom() specifies the max size of the sockaddr buffer upon input, and upon output returns the actual size of the peer address stored in the sockaddr. But you are not initializing the len variable that you pass in as the addrlen, so recvfrom() is likely to fail with an error that you do not handle.
Try something more like this instead:
Server:
#include <iostream>
#include <string.h>
#include <fstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
#define PORT 8080
int main() {
int serSockDes, readStatus;
struct sockaddr_in serAddr, cliAddr;
socklen_t cliAddrLen;
char buff[1024] = {0};
char msg[] = "Hello to you too!!!\n";
//creating a new server socket
if ((serSockDes = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket creation error...\n");
exit(-1);
}
//binding the port to ip and port
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons(PORT);
serAddr.sin_addr.s_addr = INADDR_ANY;
if ((bind(serSockDes, (struct sockaddr*)&serAddr, sizeof(serAddr))) < 0) {
perror("binding error...\n");
close(serSockDes);
exit(-1);
}
cliAddrLen = sizeof(cliAddr);
readStatus = recvfrom(serSockDes, buff, 1024, 0, (struct sockaddr*)&cliAddr, &cliAddrLen);
if (readStatus < 0) {
perror("reading error...\n");
close(serSockDes);
exit(-1);
}
cout.write(buff, readStatus);
cout << endl;
if (sendto(serSockDes, msg, strlen(msg), 0, (struct sockaddr*)&cliAddr, cliAddrLen)) < 0) {
perror("sending error...\n");
close(serSockDes);
exit(-1);
}
close(serSockDes);
return 0;
}
Client:
#include <iostream>
#include <fstream>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
#define PORT 8080
int main(int argc, char** argv) {
int cliSockDes, readStatus;
struct sockaddr_in serAddr;
socklen_t serAddrLen;
char msg[] = "Hello!!!\n";
char buff[1024] = {0};
//create a socket
if ((cliSockDes = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket creation error...\n");
exit(-1);
}
//server socket address
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons(PORT);
serAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (sendto(cliSockDes, msg, strlen(msg), 0, (struct sockaddr*)&serAddr, sizeof(serAddr)) < 0) {
perror("sending error...\n");
close(cliSockDes);
exit(-1);
}
serAddrLen = sizeof(serAddr);
readStatus = recvfrom(cliSockDes, buff, 1024, 0, (struct sockaddr*)&serAddr, &serAddrLen);
if (readStatus < 0) {
perror("reading error...\n");
close(cliSockDes);
exit(-1);
}
cout.write(buff, readStatus);
cout << endl;
close(cliSockDes);
return 0;
}
Here I am checking UDP connection of IP address with specific port by using attached code. In my code if I give any IP and any port number it is getting connected successfully, the max range of port number is 5 digit but if I give more than 5 digit it will still get connection.
Major thing is on giving failure cases to check UDP Connection it passed that cases also.
failure cases i choosed:
1)not reachable IP
2)giving any port number
please help me to figure out what mistake i did in my code and what i can do in my code to check UDP connection is available for IP with specific port.My code attached below.
Thanks in Advance
#include <cstdlib>
#include <stdio.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>
using namespace std;
int main()
{
int sockfd,rv;
struct addrinfo *servinfo, *p,hints;
struct sockaddr_in *h;
string host ="172.30.36.150";
int port=8997345;
memset(&hints, 0, sizeof hints);
struct sockaddr_in clientService;
int serversockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (serversockfd == -1) {
fprintf(stderr, "Error in socket %d\n", errno);
}
clientService.sin_family = AF_INET;
rv = getaddrinfo( host.c_str() , NULL , &hints , &servinfo);
string strhost = "";
if(rv ==0){
p = servinfo;
h = (struct sockaddr_in *) p->ai_addr;
char chost[INET_ADDRSTRLEN];
strcpy(chost , inet_ntoa( h->sin_addr ) );
strhost.append(chost);
freeaddrinfo(servinfo);
}
clientService.sin_addr.s_addr = inet_addr(strhost.c_str());
clientService.sin_port = htons((u_short)port);
int res = connect(serversockfd, (struct sockaddr*) &clientService,
sizeof(clientService));
close(serversockfd);
if (res == -1) {
fprintf(stderr, "Error connecting socket %d\n", errno);
}else{
cout<<"successfully connected"<<endl;
}
}
I am trying to make a C++ server-client communication program. Currently, both server and client are on localhost.
When I run server.cpp, it waits at "Listening...", as expected, and does not continue further till I don't run client.cpp. When client is run, server prints "Connected" and both server and client end.
But when I run client.cpp only, it prints "Connecting..." and then "Connected" after one second, even if server.cpp is not running, and specified port is not open.
I have triple checked both codes, tried them many times, also checked open ports before running only client, changed port many times, but nothing worked. Why does client say "Connected" even when server is not running?
server.cpp:
#include <cstdio>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#define PORT 11056
int main(int argc, char** argv) {
int sock = socket(AF_INET, SOCK_STREAM, PF_UNSPEC);
if (sock == -1) {
printf("E) Socket creation\n");
return 1;
}
struct sockaddr_in server, client;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = PORT;
server.sin_family = AF_INET;
int binded = bind(sock, (struct sockaddr *)&server, sizeof(server));
if (binded == -1) {
printf("E) Binding\n");
return 1;
}
printf("4) Listening...\n");
listen(sock, 5);
int new_sock = accept(sock, (struct sockaddr *)&client, (socklen_t *)sizeof(client));
printf("5) Connected\n");
shutdown(sock, SHUT_RDWR);
close(new_sock);
close(sock);
printf("EXIT\n");
return 0;
}
client.cpp
#include <cstdio>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 11056
int main(int argc, char** argv) {
int sock = socket(AF_INET, SOCK_STREAM, PF_UNSPEC);
if(sock == -1) {
printf("Error creating socket\n");
return 1;
}
struct sockaddr_in client;
client.sin_port = PORT;
client.sin_family = AF_INET;
client.sin_addr.s_addr = inet_addr("127.0.0.1");
printf("3) Connecting...\n");
connect(sock, (struct sockaddr *)&client, sizeof(client));
printf("4) Connected\n");
close(sock);
printf("EXIT");
return 0;
}