none
TCP / IP connection problem RRS feed

  • Question

  • I have a code that communicate with android application via TCP/IP protocal my code works on a fix IP (on my machine) now I want to make it mobile (work on all machines) then I want to get Server IP (local machine IP) but when i do that the code show me an Exception.

    the Exception:

    System.FormatException : 'Une adresse IP non valide a été spécifiée.'

    Mycode:

     static string send="",name1 = "", name2 = "", name3 = "", prix1 = "", prix2 = "", prix3 = "";
    
            const int PORT_NO = 7800;
           
            static string SERVER_IP ="";
            char[] data=null;
            static void Main(string[] args)
            {
               
                while (true)
                {
                    //SERVER_IP = GetIP();
                    Console.WriteLine(Dns.GetHostName());
                    IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
                    foreach (IPAddress addr in localIPs)
                    {
                        if (addr.AddressFamily == AddressFamily.InterNetwork)
                        {
    
                            Console.WriteLine(addr);
                        }
                    }
                    Console.WriteLine(SERVER_IP);
                    SERVER_IP = Dns.GetHostName().ToString();
                    string m = " * ";
                    var xx = new List<string>();
                    xx.Clear();
                    Console.ReadLine();
                    //---listen at the specified IP and port no.---
                    IPAddress localAdd = IPAddress.Parse(SERVER_IP);
                    TcpListener listener = new TcpListener(localAdd, PORT_NO);
                    Console.WriteLine("Listening...");
                    listener.Start();
                   
                    //---incoming client connected---
                    TcpClient client = listener.AcceptTcpClient();
                    Console.WriteLine("Connect...");
                    //---get the incoming data through a network stream---
    
                    NetworkStream nwStream = client.GetStream();
                    byte[] buffer = new byte[client.ReceiveBufferSize];
    
                    //---read incoming stream---
                    int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
    
                    //---convert the data received into a string---
                    string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    if (dataReceived != "")
                    {
                        var charsToRemove = new string[] { "{", "}", "Uii", "0=", ":", " " };
                        foreach (var ca in charsToRemove)
                        {
                            dataReceived = dataReceived.Replace(ca, string.Empty);
                        }
                        dataReceived = dataReceived.Substring(4);
                        string dataReceived1 = dataReceived.Substring(0, 24);
                        Console.WriteLine("Received : " + dataReceived);
                        Console.WriteLine("dataLength : " + dataReceived.Length);
    
    
                        var charsToRemove1 = new string[] { " " };
                        foreach (var ca in charsToRemove1)
                        {
                            dataReceived = dataReceived.Replace(ca, string.Empty);
                        }
                        if (dataReceived.Length < 30)
                        {
                            name1 = chargeN(dataReceived);
                            prix1 = chargeP(dataReceived);
                            m = m + "#" + name1 + "*" + prix1;
                        }
                        else
                        {
     
                            while (dataReceived.Length > 48)
                            {
                                xx.Add(dataReceived.Substring(0, 24));
                                dataReceived = dataReceived.Substring(28);
    
                            }
                            dataReceived = dataReceived.Substring(0, 24);
                            xx.Add(dataReceived);
                            int x = xx.Count;
                            Console.WriteLine("LenghtArray : " + x);
                            for (int i = 0; i < xx.Count; i++)
                            {
                                Console.WriteLine("Array ele : " + xx[i]);
                                name1 = chargeN(xx[i]);
                                prix1 = chargeP(xx[i]);
                                m = m + "#" + name1+"*"+prix1;
                            }
                            Console.WriteLine("Full array : " + m);
    
                          
                        }
                              
                            //---write back the text to the client---
                            //nwStream.Write(buffer, 0, bytesRead);
                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(m);
                            Console.WriteLine("Sending back : " + m);
                            // Send back a response.     
                            nwStream.Write(msg, 0, msg.Length);
    
                    }
    
                    client.Close();
                    listener.Stop();
                }
                
            }

    Plz help me to fix it

    Wednesday, October 16, 2019 11:24 AM

All replies

  • Listener = new TcpListener(System.Net.IPAddress.Any, portVideo);


    "I = I + 1" .. Isn't it boolshit?


    • Edited by RobbKirk Wednesday, October 16, 2019 7:23 PM
    Wednesday, October 16, 2019 7:22 PM
  • Thank u :D 
    Thursday, October 17, 2019 7:37 AM
  • Hi gaggs1, 

    Thank you for posting here.

    According to your description, you can use the following method to find IP address.

            public static string GetLocalIpAddress()
            {
                UnicastIPAddressInformation mostSuitableIp = null;
    
                var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
    
                foreach (var network in networkInterfaces)
                {
                    if (network.OperationalStatus != OperationalStatus.Up)
                        continue;
    
                    var properties = network.GetIPProperties();
    
                    if (properties.GatewayAddresses.Count == 0)
                        continue;
    
                    foreach (var address in properties.UnicastAddresses)
                    {
                        if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                            continue;
    
                        if (IPAddress.IsLoopback(address.Address))
                            continue;
    
                        if (!address.IsDnsEligible)
                        {
                            if (mostSuitableIp == null)
                                mostSuitableIp = address;
                            continue;
                        }
    
                        // The best IP is the IP got from DHCP server
                        if (address.PrefixOrigin != PrefixOrigin.Dhcp)
                        {
                            if (mostSuitableIp == null || !mostSuitableIp.IsDnsEligible)
                                mostSuitableIp = address;
                            continue;
                        }
                        return address.Address.ToString();
                    }
                }
                return mostSuitableIp != null
                    ? mostSuitableIp.Address.ToString()
                    : "";
            }

    Result:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, October 17, 2019 7:39 AM
    Moderator
  • yeah it helps thanks 
    Thursday, October 17, 2019 12:50 PM
  • You need to remember that the IP addresses you got from your network interfaces are, in virtually every case, internal to your network.  They will have no meaning in the outside world.  My computer's IP address is 192.168.192.12, but that piece of information is totally useless to anyone who is not inside our building.

    Similarly, when someone inside a network contacts a server that is outside, you can't reach back to them at that address.  If I contacted your server, my IP address would appear as 50.126.68.32, but your server cannot make a connection back to me at that address.  You'd reach our router, which would discard the connection.  Your server can certainly send stuff back on the socket I created -- the router handles that -- but you can't create a new connection.


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Thursday, October 17, 2019 8:57 PM
  • Hi gaggs1,

    Is your problem solved? if so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, October 21, 2019 9:34 AM
    Moderator