还有就是如何获取 ADSL路由器的外网IP呢?

解决方案 »

  1.   

    private void button1_Click(object sender, System.EventArgs e)
    {
    //获取本地主机名称
    string host=Dns.GetHostName();
    this.textBox1.Text=host;
               
    IPHostEntry ipHostEntry=Dns.GetHostByName(Dns.GetHostName());
    //获得本机IP地址
    IPAddress addr = new IPAddress ( ipHostEntry.AddressList [0].Address ) ;
    this.textBox2.Text=addr.ToString();
              


    }
      

  2.   

    别忘了引用这两个;
    using System.Net;
    using System.Net.Sockets;
      

  3.   

    谢谢楼上的,我要的是
    工作站(IP:192.168.1.2,DefaultGate:192.168.1.1)---》》Adsl路由器(lan ip:192.168.1.1,dhcp获取外网IP)---》》Internet
    我是想在工作站取得adsl路由器动态获取的外网IP
    大家讨论讨论如何实现吧!
    分不够,俺就加。国庆了,散分!
      

  4.   

    我有办法,因为路由器和ADSL一般都是可以通过TELNET协议进行沟通,我有源代码(C#,并测试成功,在路由器上和ADSL上,),如有兴趣,请提供邮箱
      

  5.   

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.IO;
    using System.Threading ;
    using System.Windows.Forms;namespace _YUJUNCAN
    {
    /// <summary>
    /// Summary description for clsScriptingTelnet.
    /// </summary>
    public class ScriptingTelnet
    {
    private IPEndPoint iep ;
    //private AsyncCallback callbackProc ;
    private string address ;
    private int port ;
    private int timeout;
    private string _LoginUser = string.Empty;
    private string _LoginPass = string.Empty;
    private Socket s ;
    Byte[] m_byBuff = new Byte[32767];
    private string strWorkingData = ""; // Holds everything received from the server since our last processing
    private string strFullLog = "";
    private MainForm _MainForm = null;
    private bool _Connected = false;
    private string _LastReceiveText = string.Empty;
    public string Address
    {
    get
    {
    return address;
    }
    set
    {
    if (address != value)
    {
    address = value;
    }
    }
    }
    public int Port
    {
    get
    {
    return port;
    }
    set
    {
    if (port != value)
    {
    port = value;
    }
    }
    }
    public int Timeout
    {
    get
    {
    return timeout;
    }
    set
    {
    if (timeout != value)
    {
    timeout = value;
    }
    }
    }
    public string LoginUser
    {
    get
    {
    return _LoginUser;
    }
    set
    {
    if (_LoginUser != value)
    {
    _LoginUser = value;
    }
    }
    }
    public string LoginPass
    {
    get
    {
    return _LoginPass;
    }
    set
    {
    if (_LoginPass != value)
    {
    _LoginPass = value;
    }
    }
    }
    public bool Connected
    {
    get
    {
    return _Connected;
    }
    }
    public string LastReceiveText
    {
    get
    {
    return _LastReceiveText;
    }
    }
    public MainForm mainForm 
    {
    get
    {
    return _MainForm;
    }
    } public ScriptingTelnet(string Address, int Port, int CommandTimeout,string sUser,string sPass,MainForm oMainForm)
    {
    address = Address;
    port = Port;
    timeout = CommandTimeout;
    _LoginUser = sUser;
    _LoginPass = sPass;
    this._MainForm = oMainForm;
    }

    public Socket S
    {
    get
    {
    return s;
    }
    }

    private void OnRecievedData( IAsyncResult ar )
    {
    // Get The connection socket from the callback
    Socket sock = (Socket)ar.AsyncState; // Get The data , if any
    if (sock == null || !sock.Connected)
    {
    return ;
    }
    int nBytesRec = sock.EndReceive( ar );

    if( nBytesRec > 0 )
    {
    // Decode the received data
    string sRecieved = CleanDisplay(Encoding.ASCII.GetString( m_byBuff, 0, nBytesRec )); // Write out the data
    if (sRecieved.IndexOf("[c") != -1) Negotiate(1);
    if (sRecieved.IndexOf("[6n") != -1) Negotiate(2);

    this.mainForm.ShowPanelText(sRecieved);
    this._LastReceiveText = sRecieved;
    strWorkingData += sRecieved;
    strFullLog += sRecieved;
    if (this.mainForm.AutoShow)
    {
    this.mainForm.ShowRecInfo(strWorkingData);
    } // Launch another callback to listen for data if (sock != null && sock.Connected)
    {
    AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
    sock.BeginReceive( m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData , sock );
    }

    }
    else
    {
    // If no data was recieved then the connection is probably dead
    if (sock != null && sock.Connected && this.mainForm.AutoShow)
    {
    this.mainForm.ShowRecInfo(strFullLog);
    }
    this.mainForm.ShowPanelText( "Disconnected "+sock.RemoteEndPoint.ToString() );
    sock.Shutdown( SocketShutdown.Both );
    sock.Close();
    this._Connected = s.Connected;
    //Application.Exit();
    }
    }

    private void DoSend(string strText)
    {
    try
    {
    Byte[] smk = new Byte[strText.Length];
    for ( int i=0; i < strText.Length ; i++)
    {
    Byte ss = Convert.ToByte(strText[i]);
    smk[i] = ss ;
    } s.Send(smk,0 , smk.Length , SocketFlags.None);
    }
    catch(Exception ers)
    {
    this.mainForm.ShowPanelText("ERROR IN RESPOND OPTIONS:"+ers.Message);
    }
    } private void Negotiate(int WhichPart)
    {
    StringBuilder x;
    string neg;
    if (WhichPart == 1)
    {
    x = new StringBuilder();
    x.Append ((char)27);
    x.Append ((char)91);
    x.Append ((char)63);
    x.Append ((char)49);
    x.Append ((char)59);
    x.Append ((char)50);
    x.Append ((char)99);
    neg =  x.ToString();
    }
    else
    { x = new StringBuilder();
    x.Append ((char)27);
    x.Append ((char)91);
    x.Append ((char)50);
    x.Append ((char)52);
    x.Append ((char)59);
    x.Append ((char)56);
    x.Append ((char)48);
    x.Append ((char)82);
    neg = x.ToString();
    }
    SendMessage(neg,true);
    } private string CleanDisplay(string input)
    {

    input = input.Replace("(0x (B","|");
    input = input.Replace("(0 x(B","|");
    input = input.Replace(")0=>","");
    input = input.Replace(">","");
    input = input.Replace("7","[");
    input = input.Replace("*8","]");
    input = input.Replace("","");
    return input;
    }

    public void SetServerInfo(string Address, int Port, int CommandTimeout,string sUser,string sPass)
    {
    this.address = Address;
    this.port = Port;
    this.timeout = CommandTimeout;
    this._LoginUser = sUser;
    this._LoginPass = sPass;
    }

      

  6.   

    /// <summary>
    /// Connects to the telnet server.
    /// </summary>
    /// <returns>True upon connection, False if connection fails</returns>
    public bool Connect()
    {
    this.mainForm.ShowPanelText("正在连接到路由器......");
    IPHostEntry IPHost = Dns.Resolve(address); 
    string []aliases = IPHost.Aliases; 
    IPAddress[] addr = IPHost.AddressList;  try
    {
    // Try a blocking connection to the server
    IPAddress oIPAddress = addr[0];
    if (oIPAddress.ToString() != this.address && (this.address[0] >= '0' && this.address[0] <= '9'))
    {
    oIPAddress = IPAddress.Parse(address);
    }
    s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //MessageBox.Show(oIPAddress.ToString()+","+port.ToString(),"连接信息");
    iep = new IPEndPoint(oIPAddress,port);  
    s.Connect(iep) ;
    this._Connected = s.Connected; // If the connect worked, setup a callback to start listening for incoming data
    AsyncCallback recieveData = new AsyncCallback( OnRecievedData );
    s.BeginReceive( m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData , s );

    // All is good
    this.mainForm.ShowPanelText("路由器连接成功!");
    return true;
    }
    catch(Exception eeeee )
    {
    // Something failed
    this.mainForm.ShowPanelText(eeeee.Message);
    this._Connected = s.Connected;
    this.mainForm.ShowPanelText("路由器连接失败!\n"+eeeee.Message);
    return false;
    }

    }
    public void Disconnect()
    {
    if (s.Connected) 
    {

    s.Shutdown( SocketShutdown.Both );
    s.Close();
    this._Connected = s.Connected;
    }
    } /// <summary>
    /// Waits for a specific string to be found in the stream from the server
    /// </summary>
    /// <param name="DataToWaitFor">The string to wait for</param>
    /// <returns>Always returns 0 once the string has been found</returns>
    public int WaitFor(string DataToWaitFor)
    {
    // Get the starting time
    long lngStart = DateTime.Now.AddSeconds(this.timeout).Ticks;
    long lngCurTime = 0; while (strWorkingData.ToLower().IndexOf(DataToWaitFor.ToLower()) == -1)
    {
    // Timeout logic
    lngCurTime = DateTime.Now.Ticks;
    if (lngCurTime > lngStart)
    {
    throw new Exception("Timed Out waiting for : " + DataToWaitFor);
    }
    Thread.Sleep(1);
    }
    strWorkingData = "";
    return 0;
    }


    /// <summary>
    /// Waits for one of several possible strings to be found in the stream from the server
    /// </summary>
    /// <param name="DataToWaitFor">A delimited list of strings to wait for</param>
    /// <param name="BreakCharacters">The character to break the delimited string with</param>
    /// <returns>The index (zero based) of the value in the delimited list which was matched</returns>
    public int WaitFor(string DataToWaitFor,string BreakCharacter)
    {
    // Get the starting time
    long lngStart = DateTime.Now.AddSeconds(this.timeout).Ticks;
    long lngCurTime = 0; string[] Breaks = DataToWaitFor.Split(BreakCharacter.ToCharArray());
    int intReturn = -1; while (intReturn == -1)
    {
    // Timeout logic
    lngCurTime = DateTime.Now.Ticks;
    if (lngCurTime > lngStart)
    {
    throw new Exception("Timed Out waiting for : " + DataToWaitFor);
    }

    Thread.Sleep(1);
    for (int i = 0 ; i < Breaks.Length ; i++)
    {
    if (strWorkingData.ToLower().IndexOf(Breaks[i].ToLower()) != -1)
    {
    intReturn = i ;
    }
    }
    }
    return intReturn; }
    /// <summary>
    /// Sends a message to the server
    /// </summary>
    /// <param name="Message">The message to send to the server</param>
    /// <param name="SuppressCarriageReturn">True if you do not want to end the message with a carriage return</param>
    public void SendMessage(string Message, bool SuppressCarriageReturn)
    {
    strFullLog += "\r\nSENDING DATA ====> " + Message.ToUpper() + "\r\n";
    this.mainForm.ShowPanelText("SENDING DATA ====> " + Message.ToUpper()); if (! SuppressCarriageReturn)
    {
    DoSend(Message + "\r");
    }
    else
    {
    DoSend(Message);
    }
    }
    /// <summary>
    /// Sends a message to the server, automatically appending a carriage return to it
    /// </summary>
    /// <param name="Message">The message to send to the server</param>
    public void SendMessage(string Message)
    {
    strFullLog += "\r\nSENDING DATA ====> " + Message.ToUpper() + "\r\n"; DoSend(Message + "\r");
    }
    /// <summary>
    /// Waits for a specific string to be found in the stream from the server.
    /// Once that string is found, sends a message to the server
    /// </summary>
    /// <param name="WaitFor">The string to be found in the server stream</param>
    /// <param name="Message">The message to send to the server</param>
    /// <returns>Returns true once the string has been found, and the message has been sent</returns>
    public bool WaitAndSend(string WaitFor,string Message)
    {
    this.WaitFor(WaitFor);
    SendMessage(Message);
    return true;
    }
    /// <summary>
    /// Sends a message to the server, and waits until the designated
    /// response is received
    /// </summary>
    /// <param name="Message">The message to send to the server</param>
    /// <param name="WaitFor">The response to wait for</param>
    /// <returns>True if the process was successful</returns>
    public int SendAndWait(string Message, string WaitFor)
    {
    SendMessage(Message);
    this.WaitFor(WaitFor);
    return 0;
    } public int SendAndWait(string Message, string WaitFor, string BreakCharacter)
    {
    SendMessage(Message);
    int t = this.WaitFor(WaitFor,BreakCharacter);
    return t;
    }
    /// <summary>
    /// A full log of session activity
    /// </summary>
    public string SessionLog
    {
    get 
    {
    return strFullLog;
    }
    }
    /// <summary>
    /// Clears all data in the session log
    /// </summary>
    public void ClearSessionLog()
    {
    strFullLog = "";
    strWorkingData = string.Empty;
    }
    /// <summary>
    /// Searches for two strings in the session log, and if both are found, returns
    /// all the data between them.
    /// </summary>
    /// <param name="StartingString">The first string to find</param>
    /// <param name="EndingString">The second string to find</param>
    /// <param name="ReturnIfNotFound">The string to be returned if a match is not found</param>
    /// <returns>All the data between the end of the starting string and the beginning of the end string</returns>
    public string FindStringBetween(string StartingString, string EndingString, string ReturnIfNotFound)
    {
    int intStart;
    int intEnd; intStart = strFullLog.ToLower().IndexOf(StartingString.ToLower());
    if (intStart == -1)
    {
    return ReturnIfNotFound;
    }
    intStart += StartingString.Length; intEnd = strFullLog.ToLower().IndexOf(EndingString.ToLower(),intStart); if (intEnd == -1)
    {
    // The string was not found
    return ReturnIfNotFound;
    } // The string was found, let's clean it up and return it
    return strFullLog.Substring(intStart, intEnd-intStart).Trim();
    }
    }
    }