10-03-04 02:13 AM
Hi,
I'm writing this simple program on a Linux machine using a g++ version
3.3.3 20040412 (Red Hat Linux 3.3.3-7).
[snip]
#include <iostream>
#include <string>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
using namespace std;
class obj1 {
int *p;
int sockfd;
sockaddr_in adr;
public :
obj1();
int createsock();
};
obj1::obj1() {
p=new int[2];
cout<<"port:"<<createsock();
delete [] p;
}
int obj1::createsock() {
int port1=-1;
// int reuse_addr=1;
memset((void *)&adr,0,sizeof(sockaddr_in));
adr.sin_family = AF_INET; // family
adr.sin_addr.s_addr = htonl(INADDR_ANY);// pick the current IP
address
adr.sin_port = htons(0); // pick any available port
//memset(&(adr.sin_zero), '\0', 8);
socklen_t dummyLen;
// lets start socket prging
sockfd=socket (AF_INET,SOCK_STREAM,0); // creates a socket
if(sockfd==-1)
cout<<"Problem creating socket";
if(bind (sockfd,(sockaddr *)(&adr),sizeof(sockaddr))<0)
cout<<"Error binding on socket";
if(getsockname(sockfd,(sockaddr *)(&adr),&dummyLen)<0)
cout<<"Couldnt retrieve port no";
if(listen(sockfd,2)==-1)
cout<<"Problem in listening"; // start listening man
port1=ntohs(adr.sin_port); // Set the port
return port1; // return the port! phew!
}
main()
{
obj1 n;
}
[/snip]
When I compile and run it I get
-- output------------
Couldnt retrieve port noport:0
-- end of output ----
(Error signaled is 12)
1. The funny thing is if I make the two functions as a single function
it works!
2. Also, if I remove the new and delete it works! I don't understand
how this is happening?
3. If I modify the "cout<<"port:"<<createsock();" line to
cout<<"port:"<<createsock()<<endl; Then again I get the port assigned
properly.
Why is this behavior so erratic? What mistakes am I doing?
Please help!
Thanks,
Rajat.
[ Post a follow-up to this message ]
|