[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 332
  • Last Modified:

C++ Language question

What am I doing wrong ? My code is :

include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <bstring.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <string.h>
#include <iostream.h>
#include <errno.h>
extern "C" {
      extern unsigned int inet_addr(char *string);
}

void main()
{
int SockFd,Rc,NewFd,len,lis;
int Port = 9989;
char addr[20] = "192.114.248.101";
struct sockaddr_in in;

//init sockaddr_in fields
in.sin_family = AF_INET;
cout << "in.sin_family = " << in.sin_family << "\n";
in.sin_addr.s_addr = inet_addr(addr);
cout << "in.sin_addr.s_addr = " << in.sin_addr.s_addr << "\n";
in.sin_port = htons(Port);
cout << "in.sin_port = " << in.sin_port << "\n";

// create socket
SockFd = socket(AF_INET,SOCK_STREAM,0);
cout << "SockFd is : " << SockFd << "\n";

// make the binding
//fcntl(SockFd,F_SETFL,FNDELAY);
//unlink(sin.sa_data);
Rc = bind(SockFd,(struct sockaddr_in *)&in ,sizeof(sockaddr_in));
cout << "Rc is : " << Rc << "\n";
cout << "Error is : " << strerror(errno) << "\n";

close(SockFd);
}



The result I  get is :

n.sin_family = 2
in.sin_addr.s_addr = 3228760165
in.sin_port = 9989
SockFd is : 3
Rc is : -1
Error is : Cannot assign requested address


what should i do.
0
hanan
Asked:
hanan
1 Solution
 
gaohongCommented:
Chaneg this line:

Rc = bind(SockFd,(struct sockaddr_in *)&in ,sizeof(sockaddr_in));

to

Rc = bind(SockFd,(struct sockaddr *)&in ,sizeof(sockaddr_in));

Hope this helps
gaohong xie
 
0
 
msmitsCommented:
The proposed answer helps in getting things through the compiler for me, but it still doesn't work. I don't have IRIX but Sun Solaris, but am having the same problem with your program.

I believe that the problem is with the address you are giving with the bind call. In my own code I am using INADDR_ANY, which is actually just 0. When I try your code with my own IP address, it seems to work. My conclusion is thus that you really need to specify the exact IP address of your own machine or that of localhost (127.0.0.1) or just 0.
In a server program (you are us bind) you get the address of the other side from the accept call. The bind is just to supply some information on your own side of the socket.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now