Link to home
Start Free TrialLog in
Avatar of SME_Paddington
SME_PaddingtonFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Identify IP Address source of UDP Broadcast C++

Dear Experts.

I have the following code excerpt (for illustrative purposes) and would like you to give me an example of the following:

1: Use a UDP Broadcast to output the IP address of the server that it is sent from.
2: Use this IP address to connect to said server via TCP from the client's perspective.

I attempted to write this code to output the IP address, and parse it into the variable m_szSendBuf to be sent over the network - (so that I could remote connect to this server).

cout << "1 Type a message to send (maximum 100 characters)" << endl;
      cin      >> m_szSendBuf;
      cout << "The message you have typed is: " << m_szSendBuf << endl << endl;

      InitialiseWindowsSocketsMechanism();
      cout << "Windows Socket mechanism initialised" << endl;
      CreateSocket();
      cout << "Socket created" << endl;
      SetBroadcastOption();
      cout << "Broadcast Option set" << endl;
      SetUpSendAddressStructForBroadcast();
      SetUpLocalAddressStruct();
      cout << "Broadcast Address and Port set (port " << htons(m_SendSockAddr.sin_port) << " will be used)" << endl;
      

      printf("The local sending IP address is %d.%d.%d.%d\n",
      m_LocalSockAddr.sin_addr.S_un.S_un_b.s_b1,
      m_LocalSockAddr.sin_addr.S_un.S_un_b.s_b2,
      m_LocalSockAddr.sin_addr.S_un.S_un_b.s_b3,
      m_LocalSockAddr.sin_addr.S_un.S_un_b.s_b4);
      
      SendMessage();
      cout << "Datagram sent" << endl;

      /*
      unsigned int i_octet1;
      unsigned int i_octet2;
      unsigned int i_octet3;
      unsigned int i_octet4;

      string s_octet1;
      string s_octet2;
      string s_octet3;
      string s_octet4;
      */
      
      i_octet1 = m_LocalSockAddr.sin_addr.S_un.S_un_b.s_b1;
      i_octet2 = m_LocalSockAddr.sin_addr.S_un.S_un_b.s_b2;
      i_octet3 = m_LocalSockAddr.sin_addr.S_un.S_un_b.s_b3;
      i_octet4 = m_LocalSockAddr.sin_addr.S_un.S_un_b.s_b4;

      
      stringstream s_octet1;
      //int i;
       s_octet1 << i_octet1;
       const char* p = s_octet1.str().c_str();
      cout << m_szSendBuf << endl;
      cout << i_octet1 << endl;
      cout << s_octet1 << endl;
      cout << p << endl;
      printf("%d",);

Thanks in advance for taking the time to look at my code.

Regards, SME_Paddington
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SME_Paddington

ASKER

Will give it a shot, and let you know what happens. Thanks for the tip.
Good guy, knows his stuff.