Executing linux c++ program in windows [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have seen that some of the c++ header file in windows has alternative in linux. Here I have created socket program and one more string processing program in linux-c++.
Is it possible to modify such that same code works in both windows as well in linux?
code 1:
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
//#include <sstream.h>
#include <pthread.h>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <map>
#include "dictionary_exclude.h"
#pragma GCC diagnostic ignored "-Wwrite-strings"
void *SocketHandler(void *);
int main(int argv, char **argc)
{
int host_port = 1103;
char buf[20];
int k;
struct sockaddr_in my_addr;
int hsock;
int *p_int;
int err;
socklen_t addr_size = 0;
int *csock;
sockaddr_in sadr;
pthread_t thread_id = 0;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if (hsock == -1) {
printf("Error initializing socket %dn", errno);
goto FINISH;
}
p_int = (int *) malloc(sizeof(int));
*p_int = 1;
if ((setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char *) p_int, sizeof(int)) == -1) || (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char *) p_int, sizeof(int)) == -1)) {
printf("Error setting options %dn", errno);
free(p_int);
goto FINISH;
}
free(p_int);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(hsock, (sockaddr *) & my_addr, sizeof(my_addr)) == -1) {
fprintf(stderr, "Error binding to socket, make sure nothing else is listening on this port %dn", errno);
goto FINISH;
}
if (listen(hsock, 10) == -1) {
fprintf(stderr, "Error listening %dn", errno);
goto FINISH;
}
//Now lets do the server stuff
addr_size = sizeof(sockaddr_in);
while (true) {
printf("waiting for a connectionn\n");
csock = (int *) malloc(sizeof(int));
if ((*csock = accept(hsock, (sockaddr *) & sadr, &addr_size)) != -1) {
printf("---------------------nReceived connection from %s\n", inet_ntoa(sadr.sin_addr));
pthread_create(&thread_id, 0, &SocketHandler, (void *) csock); //Pthread to manage requests from multiple clients
pthread_detach(thread_id);
} else {
fprintf(stderr, "Error accepting %dn", errno);
}
}
FINISH:
;
}
void *SocketHandler(void *lp)
{
int ar[10];
int result=0;
int *csock = (int *) lp;
char buf[20];
int k;
const unsigned int MAX_BUF_LENGTH = 4096;
std::vector<char> buffer(MAX_BUF_LENGTH);
std::string input;
int bytesReceived = 0;
//char buffer[1024];
int buffer_len = 1024;
int bytecount;
int i = 0;
std::string current;
std::vector<std::string> sentences;
if ((bytecount = recv(*csock, (char*) input.c_str(), input.length(), 0)) == -1) {
fprintf(stderr, "Error receiving data %d \n", errno);
goto FINISH;
}
do {
bytesReceived = recv(*csock, buffer.data(), buffer.size(), 0);
// append string from buffer.
if ( bytesReceived == -1 )
{
fprintf(stderr, "Error receiving data %d \n", errno);
goto FINISH;
}
else
input.append( buffer.cbegin(), buffer.cend() );
} while ( bytesReceived == MAX_BUF_LENGTH );
while(i < input.length())
{
current += input[i];
if(input[i] == '"')
{
int j = i + 1;
while( j < input.length() && input[j] != '"')
{
current += input[j];
j ++;
}
current += input[j];
i = j + 1;
}
if(input[i] == '.' || input [i] == '!' || input[i] == '?')
{
sentences.push_back(current);
current = "";
}
i ++;
}
for(i =0; i<sentences.size(); i++)
{
std::cout << i << " -> " << sentences[i] << std::endl;
}
if ((bytecount = send(*csock, (char *)ar, i *sizeof(int), 0)) == -1) { // Here we cant send lenth-1. It consider exact
fprintf(stderr, "Error sending data %d\n", errno);
goto FINISH;
}
FINISH:
free(csock);
return 0;
}
code 2:
#include<stdio.h>
#include<string.h>
#include "client.h"
int main(int argc, char *argv[] )
{
const char *buffer;
const char *ch;
std::string input = argv[1];
int ar[2];
printf("Client : \n");
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
printf( "\n%s filename\n", argv[0] );
}
else
{
ch=client(input);
ar[0]=((int*)ch)[0];
ar[1]=((int*)ch)[1];
}
printf("\n #ar[0]=%d;ar[1]=%d# \n",ar[0],ar[1]);
return ar[1];
}
header file
#include <iostream>
#ifndef client_h__
#define client_h__
extern char *client(std::string string_input);
#endif

Sockets and threads do not have a standard API used by both Windows and Linux. Although they are somewhat similar, you will have to modify your code in order to get it to work for windows.

Related

TCP Echo Server Using thread command line not showing

In my project wants when client side write like LIST the server side will directory list documents and after when I write like GET filename.txt but in the server side not shows me any thing ı think is stop how can I solve this problem my project describer in photo enter image description here
enter image description here
source code is
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdbool.h>
#include <dirent.h>
/* Definations */
#define DEFAULT_BUFLEN 1024
#define PORT 1888
void PANIC(char* msg);
#define PANIC(msg) { perror(msg); exit(-1); }
bool StartsWith(const char *a, const char *b)
{
if(strncmp(a, b, strlen(b)) == 0) return 1;
return 0;
}
void* Child(void* arg)
{ char line[DEFAULT_BUFLEN];
int bytes_read;
int client = *(int *)arg;
send(client,"Welcome to Vepa Server\n",strlen("Welcome to Vepa Server\n"),0);
do
{
bytes_read = recv(client, line, sizeof(line), 0);
if (bytes_read > 0) {
printf("%s",line);
// list command in here
if (strcmp(line,"LIST\n") ==0)
{
while(1)
{
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
send(client,dir->d_name,strlen(dir->d_name),0);
send(client,"\n",strlen("\n"),0);
}
closedir(d);
}
return(0);
}
}
if (StartsWith(line,"GET") == 1)
{
printf(line);
}
if ( (bytes_read=send(client, line, bytes_read, 0)) < 0 ) {
printf("Send failed\n");
break;
}
} else if (bytes_read == 0 ) {
printf("Connection closed by client\n");
break;
} else {
printf("Connection has problem\n");
break;
}
} while (bytes_read > 0);
close(client);
return arg;
}
int main(int argc, char *argv[])
{
int sd,opt,optval;
struct sockaddr_in addr;
unsigned short port=0;
while ((opt = getopt(argc, argv, "p:")) != -1) {
switch (opt) {
case 'p':
port=atoi(optarg);
break;
}
}
if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
PANIC("Socket");
addr.sin_family = AF_INET;
if ( port > 0 )
addr.sin_port = htons(port);
else
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = INADDR_ANY;
// set SO_REUSEADDR on a socket to true (1):
optval = 1;
setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
PANIC("Bind");
if ( listen(sd, SOMAXCONN) != 0 )
PANIC("Listen");
printf("System ready on port %d\n",ntohs(addr.sin_port));
while (1)
{
int client, addr_size = sizeof(addr);
pthread_t child;
client = accept(sd, (struct sockaddr*)&addr, &addr_size);
printf("Connected: %s:%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
if ( pthread_create(&child, NULL, Child, &client) != 0 )
perror("Thread creation");
else
pthread_detach(child); /* disassociate from parent */
}
return 0;
}

Telnet client error in c++

The telnet client code is :
enter code here
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <termios.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/telnet.h>
#define DO 0xfd
#define WONT 0xfc
#define WILL 0xfb
#define DONT 0xfe
#define CMD 0xff
#define CMD_ECHO 1
#define CMD_WINDOW_SIZE 31
void negotiate(int sock, unsigned char *buf, int len) {
int i;
if (buf[1] == DO && buf[2] == CMD_WINDOW_SIZE) {
unsigned char tmp1[10] = {255, 251, 31};
if (send(sock, tmp1, 3 , 0) < 0)
exit(1);
unsigned char tmp2[10] = {255, 250, 31, 0, 80, 0, 24, 255, 240};
if (send(sock, tmp2, 9, 0) < 0)
exit(1);
return;
}
for (i = 0; i < len; i++) {
if (buf[i] == DO)
buf[i] = WONT;
else if (buf[i] == WILL)
buf[i] = DO;
}
if (send(sock, buf, len , 0) < 0)
exit(1);
}
static struct termios tin;
static void terminal_set(void) {
// save terminal configuration
tcgetattr(STDIN_FILENO, &tin);
static struct termios tlocal;
memcpy(&tlocal, &tin, sizeof(tin));
cfmakeraw(&tlocal);
tcsetattr(STDIN_FILENO,TCSANOW,&tlocal);
}
static void terminal_reset(void) {
// restore terminal upon exit
tcsetattr(STDIN_FILENO,TCSANOW,&tin);
}
#define BUFLEN 20
int main(int argc , char *argv[]) {
int sock;
struct sockaddr_in server;
unsigned char buf[BUFLEN + 1];
int len;
int i;
if (argc < 2 || argc > 3) {
printf("Usage: %s address [port]\n", argv[0]);
return 1;
}
int port;
if (argc == 3)
port = atoi(argv[2]);
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1) {
perror("Could not create socket. Error");
return 1;
}
server.sin_addr.s_addr = inet_addr(argv[1]);
server.sin_family = AF_INET;
server.sin_port = htons(port);
//Connect to remote server
if (connect(sock , (struct sockaddr*)&server , sizeof(server)) < 0) {
perror("connect failed. Error");
return 1;
}
puts("Connected...\n");
// set terminal
terminal_set();
atexit(terminal_reset);
struct timeval ts;
ts.tv_sec = 1; // 1 second
ts.tv_usec = 0;
while (1) {
// select setup
fd_set fds;
FD_ZERO(&fds);
if (sock != 0)
FD_SET(sock, &fds);
FD_SET(0, &fds);
// wait for data
int nready = select(sock + 1, &fds, (fd_set *) 0, (fd_set *) 0, &ts);
if (nready < 0) {
perror("select. Error");
return 1;
}
else if (nready == 0) {
ts.tv_sec = 1; // 1 second
ts.tv_usec = 0;
}
else if (sock != 0 && FD_ISSET(sock, &fds)) {
// start by reading a single byte
int rv;
if ((rv = recv(sock , buf , 1 , 0)) < 0)
return 1;
else if (rv == 0) {
printf("Connection closed by the remote end\n\r");
return 0;
}
if (buf[0] == CMD) {
// read 2 more bytes
len = recv(sock , buf + 1 , 2 , 0);
if (len < 0)
return 1;
else if (len == 0) {
printf("Connection closed by the remote end\n\r");
return 0;
}
negotiate(sock, buf, 3);
}
else {
len = 1;
buf[len] = '\0';
printf("%s", buf);
fflush(0);
}
}
else if (FD_ISSET(0, &fds)) {
buf[0] = getc(stdin); //fgets(buf, 1, stdin);
if (send(sock, buf, 1, 0) < 0)
return 1;
if (buf[0] == '\n') // with the terminal in raw mode we need to force a LF
putchar('\r');
}
}
close(sock);
return 0;
}
While the server code is :
enter code here
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
int main(int argc , char *argv[])
{
int socket_desc , new_socket , c;
struct sockaddr_in server ,client;
char *message;
//create socket;
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{printf("Could not create socket");
}
//prepare sock addr structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//bind
if(bind(socket_desc, (struct sockaddr *)&server , sizeof(&server)) < 0)
{
printf("bind failed");
}
printf("Bind done");
//Listen
listen(socket_desc , 3);
//accept incoming connection
printf("Waiting for incoming connection ... ");
c =sizeof(struct sockaddr_in);
new_socket = accept(socket_desc, (struct sockaddr *)&client,sizeof(&client));
while(new_socket < 0);
{
puts("Connection Accepted");
message = "Hello Client ...Recieved your message \n";
write(new_socket , message , strlen(message));
}
if (new_socket < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
On executing the programs from command line :
./server 8000
./telnet_client 127.0.0.1 8000
The telnet client gives the error "Connect failed.Error:Connection refused"
Kindly help how to successfully execute the program
You are listening on 8888 port but trying to connect to 8000. Although you are passing 8000 parameter to server program you don't do anything with it. To correct this don't hard code
server.sin_port = htons( 8888 );
but instead process parameters passed to the program
if ( argc != 2)
err_quit("usage: server <port>"); // or maybe use some default
//...
server.sin_port = htons( atoi( argv[1]) );
in the server
int port = 8888;
...
if (argc < 1 || argc > 2) {
printf("Usage: %s [port(default=8888)] \n", argv[0]);
return 1;
}
port = (argc == 2) ? atoi(argv[1]);
...
server.sin_port = htons(port);
...

Performing sequential send and receive operation in TCP socket programming

I am trying to implement Socket where client send sentence to server and server replies back two integer valeus pcount and ncount. I can receive both this but first recv operation receives both values and also appends some other data to buffer.
Client.cpp
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
char *foo(char* buf)
{
char buffer[1024];
char *a='\0';
char *c=buf;
strcpy(buffer,buf);
int host_port= 1102;
char* host_name="127.0.0.1";
struct sockaddr_in my_addr;
//char buffer[1024];
int bytecount;
int buffer_len=0;
int hsock;
int * p_int;
int err;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if(hsock == -1){
printf("Error initializing socket %d\n",errno);
goto FINISH;
}
p_int = (int*)malloc(sizeof(int));
*p_int = 1;
if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
(setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
printf("Error setting options %d\n",errno);
free(p_int);
goto FINISH;
}
free(p_int);
my_addr.sin_family = AF_INET ;
my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = inet_addr(host_name);
if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){
if((err = errno) != EINPROGRESS){
fprintf(stderr, "Error connecting socket %d\n", errno);
goto FINISH;
}
}
//Now lets do the client related stuff
buffer_len = 1024;
memset(buf, '\0', buffer_len);
buf[strlen(buf)-1]='\0';
if( (bytecount=send(hsock, buffer, strlen(buffer),0))== -1){
fprintf(stderr, "Error sending data %d\n", errno);
go
to FINISH;
}
printf("Sent bytes %d\n", bytecount);
//-------
// may Needs to empty content of buffer here but dont know how to do. Tried with fflush, free(buffer) but does not work
//Two recv function which ideally recv pcount and ncount subsequently
if((bytecount = recv(hsock, buffer, buffer_len, 0))== -1){
fprintf(stderr, "Error receiving data %d\n", errno);
goto FINISH;
}
printf("Recieved bytes %d\nReceived string \"%s \n", bytecount, buffer);
//Needs to empty content of buffer here but dont know how to do. Tried with fflush, free(buffer) but does not work
if((bytecount = recv(hsock, buffer, buffer_len, 0))== -1){
fprintf(stderr, "Error receiving data %d\n", errno);
goto FINISH;
}
printf("Recieved bytes %d\nReceived string \"%s \n", bytecount, buffer);
close(hsock);
FINISH:
;
return buffer;
}
And server.cpp :
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
//#include <errno.h>
#include <stdio.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <unistd.h>
//#include <sstream.h>
#include <pthread.h>
#include "serverFunction.cpp"
#include "serverFunction2.cpp"
#include <iostream>
#include <sstream>
#include <cstdio>
using namespace std;
void *SocketHandler(void *);
int main(int argv, char **argc)
{
int host_port = 1102;
char buf[20];
int k;
struct sockaddr_in my_addr;
int hsock;
int *p_int;
int err;
socklen_t addr_size = 0;
int *csock;
sockaddr_in sadr;
pthread_t thread_id = 0;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if (hsock == -1) {
printf("Error initializing socket %dn", errno);
goto FINISH;
}
p_int = (int *) malloc(sizeof(int));
*p_int = 1;
if ((setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char *) p_int, sizeof(int)) == -1) || (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char *) p_int, sizeof(int)) == -1)) {
printf("Error setting options %dn", errno);
free(p_int);
goto FINISH;
}
free(p_int);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(hsock, (sockaddr *) & my_addr, sizeof(my_addr)) == -1) {
fprintf(stderr, "Error binding to socket, make sure nothing else is listening on this port %dn", errno);
goto FINISH;
}
if (listen(hsock, 10) == -1) {
fprintf(stderr, "Error listening %dn", errno);
goto FINISH;
}
//Now lets do the server stuff
addr_size = sizeof(sockaddr_in);
while (true) {
printf("waiting for a connectionn\n");
csock = (int *) malloc(sizeof(int));
if ((*csock = accept(hsock, (sockaddr *) & sadr, &addr_size)) != -1) {
printf("---------------------nReceived connection from %s\n", inet_ntoa(sadr.sin_addr));
pthread_create(&thread_id, 0, &SocketHandler, (void *) csock);
pthread_detach(thread_id);
} else {
fprintf(stderr, "Error accepting %dn", errno);
}
}
FINISH:
;
}
void *SocketHandler(void *lp)
{
int result=0;
//std::stringstream ss;
int *csock = (int *) lp;
char buf[20];
int k;
// char *target="my name is khan";
char *str;
char *str2;
int pcount = 0, ncount = 0;
char buffer[1024];
int buffer_len = 1024;
int bytecount;
int i = 0,t=0,q=0;
int j = 0;
char *ch[50] = { 0 }; /* stores references to 50 words. */
char *ch2[50] = { 0 };
char *word = strtok(buffer, " ");
char *word2 = strtok(buffer, " ");
char *portstring1=(char *)malloc(sizeof(buffer));
char *portstring2=(char *)malloc(sizeof(buffer));
memset(buffer, 0, buffer_len);
if ((bytecount = recv(*csock, buffer, buffer_len, 0)) == -1) {
fprintf(stderr, "Error receiving data %d \n", errno);
goto FINISH;
}
printf("Received bytes %d \n Received string %s \n ", bytecount, buffer);
/* stores references to 50 words. */
word = strtok(buffer, " ");
while ((NULL != word) && (50 > i)) {
ch[i] = strdup(word);
//printf("%s n", ch[i]);
str = BoyerMoore_positive(ch[i], strlen(ch[i]) - 1);
str2= BoyerMoore_negative(ch[i], strlen(ch[i]) - 1);
if (str == NULL)
t++;
else {
printf("%s \n", ch[i]);
// puts("true");
pcount += 1;
printf("Positive count is: %d \n",pcount);
}
if(str2== NULL)
q++;
else {
printf("%s \n", ch[i]);
// puts("true");
ncount += 1;
printf("Nagative count is: %d \n",ncount);
}
i++;
word = strtok(NULL, " ");
}
//I want to send pcount and ncount values to client
**sprintf(portstring1, "%d", pcount);
if ((bytecount = send(*csock, portstring1, 1, 0)) == -1) {
fprintf(stderr, "Error sending data %d\n", errno);
goto FINISH;
}
sprintf(portstring2, "%d", ncount);
if ((bytecount = send(*csock, portstring2, strlen(portstring2), 0)) == -1) {
fprintf(stderr, "Error sending data %d\n", errno);
goto FINISH;
}**
FINISH:
free(csock);
return 0;
}
I receive output like this:
Enter sentence to send to the server (press enter)
critic worst nice
Sent bytes 18
Recieved bytes 2
Received string 12itic worst nice //Here there should be only 1 2. Why 'itic ..' gets appended. And why 1 and 2 both does not get printed one after another
You forgot to design and implement a protocol. Network communication doesn't work by magic. If you have a notion of an application-level message, you have to write code to send and receive application-level messages. You haven't done this, so of course it won't happen.
Also:
printf("Received bytes %d \n Received string %s \n ", bytecount, buffer);
The %s format specifier is only for C-style strings. It's not suitable for arbitrary data. How would it know how many bytes to print?
The recv function does not add a nul character to terminate the received string. You have to add it yourself, like this:
if((bytecount = recv(hsock, buffer, buffer_len-1, 0))== -1){
fprintf(stderr, "Error receiving data %d\n", errno);
goto FINISH;
}
buffer[bytecount]=0;
Notice the -1 in buffer len, to make sure there's room for the nul character.
#Joni and David- Thanks for your support!
Problem solved:
at sender:
int ar[2];
if ((bytecount = send(*csock, (char *)ar, 2 *sizeof(int), 0)) == -1) { // Here we cant send lenth-1. It consider exact
fprintf(stderr, "Error sending data %d\n", errno);
goto FINISH;
}
at receiver side:
if((bytecount = recv(hsock, ar, 2 * sizeof(int), 0))== -1){
fprintf(stderr, "Error receiving data %d\n", errno);
goto FINISH;
}
for(k=0;k<2;k++)
{
printf("count is :%d",ar[k]);
}
just took and array, Now I can send any receive any numbers of values! It's so easy!

Portable compact representation of IP address

I have a C++ program using the Berkley sockets API on Linux. I have one end of the connection sending two IP addresses to the client. I can represent these using inet_ntop() and inet_pton(), but this would make the message length 2*INET6_ADDRSTRLEN, which is 92 bytes. That seems a little much for two IP addresses. Is there a portable, compact binary representation of IP addresses (it must work with both IPv4 and IPv6).
If you have an addrinfo lying around, then send the .ai_addr and .ai_addrlen.
Try these two programs:
send_sockaddr.cc:
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <cstdio>
#include <cerrno>
#include <cstdlib>
int main (int ac, char **av) {
if(ac != 3) {
fprintf(stderr, "Usage: %s hostname portnumber\n", *av);
return 1;
}
struct addrinfo *res0;
struct addrinfo hints = { AI_CANONNAME, 0, SOCK_DGRAM };
int rc = getaddrinfo(av[1], av[2], &hints, &res0);
if(rc) {
fprintf(stderr, "%s/%s: %s\n", av[1], av[2], gai_strerror(rc));
return 1;
}
char *name = res0->ai_canonname;
for(struct addrinfo *res = res0; res; res=res->ai_next) {
fprintf(stderr, "%s: %04X/%04X/%04X ", name, res->ai_family, res->ai_socktype, res->ai_protocol);
int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(fd < 0) {
perror("socket");
continue;
}
rc = connect(fd, res->ai_addr, res->ai_addrlen);
if(rc < 0) {
perror("connect");
continue;
}
fprintf(stderr, "Connected (%d)\n", fd);
*(unsigned short*)res->ai_addr = htons(*(unsigned short*)res->ai_addr);
rc = send(fd, res->ai_addr, res->ai_addrlen, 0);
*(unsigned short*)res->ai_addr = ntohs(*(unsigned short*)res->ai_addr);
if(rc < 0) {
perror("send");
}
close(fd);
}
freeaddrinfo(res0);
}
listen_sockaddr.cc:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <cstdio>
#include <cerrno>
#include <cstdlib>
#include <poll.h>
#include <vector>
#include <arpa/inet.h>
int main (int ac, char **av) {
if(ac != 2) {
fprintf(stderr, "Usage: %s portnumber\n", *av);
return 1;
}
struct addrinfo *res0;
struct addrinfo hints = { 0, 0, SOCK_DGRAM };
int rc = getaddrinfo(0, av[1], &hints, &res0);
if(rc) {
fprintf(stderr, "%s/%s: %s\n", av[1], av[2], gai_strerror(rc));
return 1;
}
char *name = res0->ai_canonname;
std::vector<pollfd> fds;
for(struct addrinfo *res = res0; res; res=res->ai_next) {
fprintf(stderr, "%s: ", name);
int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(fd < 0) {
perror("socket");
continue;
}
rc = bind(fd, res->ai_addr, res->ai_addrlen);
if(rc < 0) {
perror("bind");
continue;
}
fprintf(stderr, "Bound (%d)\n", fd);
fds.push_back(pollfd({fd, POLLIN}));
}
freeaddrinfo(res0);
while( (rc = poll( &fds[0], fds.size(), -1)) > 0 ) {
for(size_t i = 0; i < fds.size(); ++i) {
pollfd& pfd = fds[i];
if(!pfd.revents)
continue;
pfd.revents = 0;
union {
sockaddr s;
sockaddr_in sin;
sockaddr_in6 sin6;
} u;
rc = recv(pfd.fd, &u, sizeof u, 0);
if(rc < 0) {
perror("recv");
continue;
}
fprintf(stderr, "Received %d bytes\n", rc);
char str[256];
switch(ntohs(u.s.sa_family)) {
case AF_INET:
if(inet_ntop(AF_INET, &u.sin.sin_addr, str, sizeof str)) {
fprintf(stderr, "AF_INET %s\n", str);
} else {
fprintf(stderr, "AF_INET unknown\n");
}
break;
case AF_INET6:
if(inet_ntop(AF_INET6, &u.sin6.sin6_addr, str, sizeof str)) {
fprintf(stderr, "AF_INET6 %s\n", str);
} else {
fprintf(stderr, "AF_INET6 unknown\n");
}
break;
default:
fprintf(stderr, "UNKNOWN\n");
break;
}
}
}
}
Actually, IP addresses aren't numbers itself, so the byte representation would always follow Big-Endian. At least I don't know any platform where this is different. It's just not handled as a number, but as 4 bytes.

Could you recommend some guides about Epoll on Linux [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I need to know about Epoll On linux System.
Could you recommend manual or guides about epoll library?
need more detailed guides. it's better to have some examples.
help me. and Thank you for reading.
Here's an introduction to Epoll, a pretty basic tutorial: http://blog.kovyrin.net/2006/04/13/epoll-asynchronous-network-programming/
A more complete example can be found here: https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/
Also, the man pages
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#define PORT 1500
#define MAX_CON (1200)
static struct epoll_event *events;
int main(int argc, char *argv[])
{
fd_set master;
fd_set read_fds;
struct sockaddr_in serveraddr;
struct sockaddr_in clientaddr;
int fdmax;
int listener;
int newfd;
char buf[1024];
int nbytes;
int addrlen;
int yes;
int epfd = -1;
int res = -1;
struct epoll_event ev;
int i=0;
int index = 0;
int client_fd = -1;
int SnumOfConnection = 0;
time_t Sstart, Send;
if((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("Server-socket() error lol!");
exit(1);
}
if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
perror("Server-setsockopt() error lol!");
exit(1);
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = INADDR_ANY;
serveraddr.sin_port = htons(PORT);
memset(&(serveraddr.sin_zero), '\0', 8);
if(bind(listener, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == -1)
{
perror("Server-bind() error lol!");
exit(1);
}
if(listen(listener, 10) == -1)
{
perror("Server-listen() error lol!");
exit(1);
}
fdmax = listener; /* so far, it's this one*/
events = calloc(MAX_CON, sizeof(struct epoll_event));
if ((epfd = epoll_create(MAX_CON)) == -1) {
perror("epoll_create");
exit(1);
}
ev.events = EPOLLIN;
ev.data.fd = fdmax;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fdmax, &ev) < 0) {
perror("epoll_ctl");
exit(1);
}
//time(&start);
for(;;)
{
res = epoll_wait(epfd, events, MAX_CON, -1);
client_fd = events[index].data.fd;
for (index = 0; index < MAX_CON; index++) {
if(client_fd == listener)
{
addrlen = sizeof(clientaddr);
if((newfd = accept(listener, (struct sockaddr *)&clientaddr, &addrlen)) == -1)
{
perror("Server-accept() error lol!");
}
else
{
// printf("Server-accept() is OK...\n");
ev.events = EPOLLIN;
ev.data.fd = newfd;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, newfd, &ev) < 0) {
perror("epoll_ctl");
exit(1);
}
}
break;
}
else
{
if (events[index].events & EPOLLHUP)
{
if (epoll_ctl(epfd, EPOLL_CTL_DEL, client_fd, &ev) < 0) {
perror("epoll_ctl");
}
close(client_fd);
break;
}
if (events[index].events & EPOLLIN) {
if((nbytes = recv(client_fd, buf, sizeof(buf), 0)) <= 0)
{
if(nbytes == 0) {
// printf("socket %d hung up\n", client_fd);
}
else {
printf("recv() error lol! %d", client_fd);
perror("");
}
if (epoll_ctl(epfd, EPOLL_CTL_DEL, client_fd, &ev) < 0) {
perror("epoll_ctl");
}
close(client_fd);
}
else
{
if(send(client_fd, buf, nbytes, 0) == -1)
perror("send() error lol!");
}
break;
}
}
}
}
return 0;
}
I wrote this program for testing and I was able to connect more than 80k connections and I find average system load only to 0.27%.