我正在制作一个客户端,连接到本地托管的服务器,从服务器获得股票编号。如果我使用下面的代码,这个程序确实可以工作,但它的工作方式是通过获取dns名称,所以理论上它只需要www.website.com,而我不知道如何让它识别127.0.0.1的普通ip或本地主机IP:
IPHostEntry ipHostInfo = Dns.GetHostEntry("www.website.com");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);附件是我的尝试,以解决ip,但我不认为我正在接近这个权利,完整的代码可以在这里看到:StockReader Client Code
public class AsynchronousClient
{
private const int port = 21;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
//******************ISSUE BEGINS HERE*********************************
string sHostName = Dns.GetHostName();
IPHostEntry ipHostInfo = Dns.GetHostEntry(sHostName);
IPAddress [] ipAddress = ipHostInfo.AddressList;
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test<EOF>");
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}发布于 2011-01-27 09:01:03
设置ipAddress的值时,可以使用IPAddress.Parse方法传入字符串并检索IPAddress对象,而不是使用域名:
string ip = "127.0.0.1";
IPAddress address = IPAddress.Parse(ipAddress);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);发布于 2011-01-27 09:09:00
尝试使用string sHostName = "localhost";
发布于 2017-05-10 11:42:03
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, portnumber);
// Create a TCP/IP socket.
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(remoteEP);https://stackoverflow.com/questions/4811834
复制相似问题