C socket: Connection refused[Errno 111] - sockets

I'm writing a simple socket server/client. Here is the server part:
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
using namespace std;
int main() {
int listenfd;
int connfd;
sockaddr_in servaddr;
char buf[100];
time_t ticks;
if(listenfd = socket(AF_INET,SOCK_STREAM,0) < 0)
cout << "listenfd" << endl;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(10000);
bind(listenfd,(const struct sockaddr*)&servaddr,sizeof(servaddr));
listen(listenfd,5);
for(;;) {
connfd = accept(listenfd,(struct sockaddr *)NULL,NULL);
//cout << "accept link" << endl;
ticks = time(NULL);
snprintf(buf,sizeof(buf),"%.24s\r\n",ctime(&ticks));
//cout << buf << endl;
write(connfd,buf,strlen(buf));
close(connfd);
}
}
And here is the client part:
#include <netinet/in.h>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <arpa/inet.h>
using namespace std;
#define MAX 100
int main(int argc,char **argv) {
int socketfd;
int n;
char buf[MAX+1];
sockaddr_in servaddr;
if(argc !=2 )
cout << "stdin error " << endl;
if((socketfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
cout << " socekt error " << endl;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(10000);
if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr) <= 0)
cout << "inet_pton error" << endl;
cout << "prepare linking" << endl;
if(connect(socketfd,(const struct sockaddr*)&servaddr,sizeof(struct sockaddr)) < 0)
{
cout << " connet error" << endl;
cout << strerror(errno);
}
while((n = read(socketfd,buf,MAX)) >0) {
buf[n] = 0;
if(fputs(buf,stdout) == EOF)
cout << "cout error" << endl;
}
if(n < 0)
cout << "read error" << endl;
exit(0);
}
I start the server first and run the client like: ./client 127.0.0.1, but connection failed with errno 111.
I'm using Ubuntu 12.04 system.

In your server code, you have:
if(listenfd = socket(AF_INET,SOCK_STREAM,0) < 0)
The problem is to do with the precedence of C operators. Because the < comparison has a higher precedence than assignment, your statement will set listenfd to the boolean value of the x < y bit meaning, because the socket will most likely succeed, it will most likely be set to 0 (false), hence standard input (file descriptor 0).
If you must use the C shortcuts (I know they're handy but sometimes they're less readable than the alternatives), you should use the variant:
if ((listenfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
as you have already done in your client code:
if ((socketfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)

Related

I can't fragment my packet on a TCP connection

I've been trying and trying to fragment my TCP packets but I havent found any helpful implementation of it. I am familiar with the theory and concepts of fragmentation, have even come across some flags such as IP_PMTUDISC_DONT, IP_PMTUDISC_WANT, and IP_PMTUDISC_DO and set them but the wireshark's capture always showed DF Flag as on.
I've set the MTU of my 'lo' Network Interface to 1500 since I'm using LoopBack Address on both, the server and the client. And I thought that fragmentation will be handled by the Network Layer, but thats not the case I guess...
Please help me with fragmentation of the packet.Here's my code...
Server.cpp
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netdb.h>
int main(){
struct sockaddr_in serv_addr, cli_addr;
char buff[255];
int FileDesc = socket(AF_INET,SOCK_STREAM, 0);
if(FileDesc < 0){
perror("Socket Creation Failed. ");
exit(EXIT_FAILURE);
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(5455);
if (bind(FileDesc, (const sockaddr*)&serv_addr, sizeof(serv_addr)) < 0){
perror("Bind Failed.");
exit(EXIT_FAILURE);
}
if (listen(FileDesc, 6) < 0){
perror("Listen Failed.");
exit(EXIT_FAILURE);
}
socklen_t cliLen;
int AcceptFD = accept(FileDesc, (sockaddr*)&cli_addr, &cliLen);
if(AcceptFD < 0){
perror("Accept Failed.");
exit(EXIT_FAILURE);
}
//Setting the MTU
struct ifreq ifr;
ifr.ifr_addr.sa_family = AF_INET;//address family
strncpy(ifr.ifr_name, "lo", sizeof(ifr.ifr_name));//interface name where you want to set the MTU
ifr.ifr_mtu = 1500; //your MTU size here
if (ioctl(FileDesc, SIOCGIFMTU, (caddr_t)&ifr) < 0){
perror("ioctl error.");
exit(1);
}
std::cout << ifr.ifr_ifru.ifru_mtu;
while(1){
//File Transfer
}
close(AcceptFD);
close(FileDesc);
return 0;
}
Client.cpp
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <arpa/inet.h>
int main(){
struct sockaddr_in serv_addr;
char buffer[255];
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0){
perror("Socket Creation Failed.");
exit(EXIT_FAILURE);
}
FILE *fp;
char *filename = "File.txt";
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
inet_aton("127.0.0.1", &serv_addr.sin_addr);
serv_addr.sin_port = htons(5455);
int conn = connect(fd, (const sockaddr*)&serv_addr, sizeof(serv_addr));
if (conn < 0){
perror("Connect Failed. ");
exit(EXIT_FAILURE);
}
while(1){
//File Recieve
}
close(fd);
return 0;
}
This also begs the question, how would I re-assemble my packet back in the same order?
Thank youu.

Tcp socket using C (server)

I coded a program in C of a tcp socket but once executed, the server returns an error from the accept function but i can't find out why..
If you guys can help me, that would be appreciated. Also, if you have any advice on the way i programmed this, please feel free to tell me.
Here is my code :
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
int listenSocket, status, socketClient;
unsigned short int msgLength;
struct addrinfo hints, *servinfo;
struct sockaddr_in clientAddress;
socklen_t clientAddressLength = sizeof clientAddress;
char msg[101];
//Test port number
if (argc != 2) {
fprintf(stderr,"Usage : %s [NUMERO_PORT]\n",argv[0]);
return 2;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET; // IPv4
hints.ai_socktype = SOCK_DGRAM; // UDP
hints.ai_flags = 0; //Car on fait le test sur la meme machine
if ((status = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 3;
}
if ((listenSocket = socket(servinfo->ai_family, servinfo-
>ai_socktype, servinfo->ai_protocol)) == -1) {
perror("socket:");
return 4;
}
if (bind(listenSocket, servinfo->ai_addr, servinfo->ai_addrlen) ==
-1) {
close(listenSocket);
perror("bind:");
return 5;
}
listen(listenSocket,5);
int sizeOfSockAddr = sizeof(clientAddress);
socketClient= accept(listenSocket, NULL, NULL);
if (socketClient < 0) {
fprintf(stderr,"Erreur accept\n");
return 6;
}
freeaddrinfo(servinfo);
printf("Waiting for a client's request %s\n", argv[1]);
while (1) {
//some things
}
}`

UDP client on a OS X

I wanted to compile sample code for a UDP client on a Mac OS X, but got a following error:
client.c:91:9: error: use of undeclared identifier 'MSG_CONFIRM'
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
^
I googled for the error for several hours but couldn't find anything related to this problem. Does anybody know what is the issue and how to fix it?
The code for UDP client is below
// 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>
#include <netdb.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;
int n, len;
sendto(sockfd, (const char *)hello, strlen(hello),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("Hello message sent.\n");
while (1)
{
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, (struct sockaddr *) &servaddr,
&len);
buffer[n] = '\0';
printf("Server : %s\n", buffer);
}
close(sockfd);
return 0;
}
My friend suggest me to define MSG_CONFIRM as 0. He said search what is use for it. You also research it.
#define MSG_CONFIRM 0

Thrust Device Vector iterator location

i am trying to find the index/location of an iterator, i use the thrust::distance(). however, it returns weird value.
the vector size is 10. and when i use this method it returns value of "131" .
here is a fully working example.
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/random.h>
#include <thrust/unique.h>
#include <thrust/reduce.h>
#include <thrust/iterator/constant_iterator.h>
using namespace std;
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, ""));
std::cout << std::endl;
}
int main()
{
thrust::device_vector<int> x;
x.push_back(1);
x.push_back(10);
x.push_back(1);
x.push_back(11);
x.push_back(1);
x.push_back(11);
thrust::device_vector<int> y(10);
print_vector("Original",x);
thrust::sort(x.begin(),x.end());
print_vector("sort",x);
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
std::cout<<*it<<std::endl;
//int newsize=it-y.begin();
int newsize=thrust::distance(y.begin(),it);
cout<<"nsz:"<<newsize<<endl;
return 0;
}
The iterator it is established with respect to the vector x:
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
^ ^
But you are asking for the distance from this iterator to the beginning of the vector y:
int newsize=thrust::distance(y.begin(),it);
^
That doesn't make sense. There is no defined relationship between it and the vector y.
If you ask for the distance to the beginning of vector x instead, you'll get more sensible results:
$ cat t1244.cu
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/random.h>
#include <thrust/unique.h>
#include <thrust/reduce.h>
#include <thrust/iterator/constant_iterator.h>
using namespace std;
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
int main()
{
thrust::device_vector<int> x;
x.push_back(1);
x.push_back(10);
x.push_back(1);
x.push_back(11);
x.push_back(1);
x.push_back(11);
thrust::device_vector<int> y(10);
print_vector("Original",x);
thrust::sort(x.begin(),x.end());
print_vector("sort",x);
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
std::cout<<*it<<std::endl;
//int newsize=it-y.begin();
int newsize=thrust::distance(x.begin(),it);
cout<<"nsz:"<<newsize<<endl;
return 0;
}
$ nvcc -o t1244 t1244.cu
$ ./t1244
Original 1 10 1 11 1 11
sort 1 1 1 10 11 11
10
nsz:3
$

Coding UDP Socket in C - sendto Invalid Arguments

I'm actually back to programming in C, and I want to code a UDP Client.
My problem is that I'm having an error when executing the sendto function... getting errno : 22 and the message error : Invalid argument
char query[1024];
int querySize = strlen(query);
SOCKADDR_IN dest = { 0 };
int destSize = sizeof dest;
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr('192.168.0.3');
dest.sin_port = htons(6000);
sendto(sock, query, querySize, 0, (SOCKADDR *) &dest, destSize)
Hope someone could help me?
Here is my full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#if defined (WIN32)
#include <winsock2.h>
typedef int socklen_t;
#elif defined (linux)
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket(param) close(param)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
#endif
int main(int argc, char *argv[]) {
#if defined (WIN32)
WSADATA WSAData;
WSAStartup(MAKEWORD(2,2), &WSAData);
#endif
char source_ip[15] = "192.168.0.20";
int source_port = 5000;
char query[1024];
printf("- Opening Socket\n");
SOCKET sock;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock == INVALID_SOCKET) {
perror("[ERROR] socket()");
exit(errno);
}
printf("- Configuring socket source to : [%s:%d]\n", source_ip, source_port);
SOCKADDR_IN source;
source.sin_family = AF_INET;
source.sin_addr.s_addr = inet_addr(source_ip);
source.sin_port = htons(source_port);
if(bind(sock, (SOCKADDR *)&source, sizeof(source)) == SOCKET_ERROR) {
perror("[ERROR] bind()");
exit(errno);
}
int querySize = strlen(query);
SOCKADDR_IN dest = { 0 };
int destSize = sizeof dest;
dest.sin_family = AF_INET;
printf("- Sending packets\n");
dest.sin_addr.s_addr = inet_addr('192.168.0.3');
dest.sin_port = htons(6000);
if(sendto(sock, query, querySize, 0, (SOCKADDR *) &dest, destSize) < 0) {
perror("[ERROR] sendto()");
printf("%d\n", errno);
exit(errno);
}
printf("\n\n##############################\n");
printf("Closing socket ...\n");
closesocket(sock);
#if defined (WIN32)
WSACleanup();
#endif
printf("Program finished.\n");
return 0;
}
Did you notice,
that query is not being initialized?
So strlen(query) might result in a "very long" buffer.
That would be a good candidate for an EINVAL.