C & C++/MFC Network
[IP] 네트워크 관련
izen8
2011. 1. 13. 14:34
IP 주소 컨트롤 변환 방법
- 1. IP 문자열을 32비트로...
// 인자로 전달받은 문자열에 해당하는 IP 주소를 32비트로 변환
DWORD dwAddress = inet_addr("10.1.1.100");
- 2. 32비트를 IP 문자열로...
// 네트워크 순서로 정렬된 값을 호스트 순서로 변환
DWORD dwAddress = ntohl(m_dwAddress);
// 입력받은 32비트 IP 주소를 문자열로 변환
strTmp = inet_ntoa(*(IN_ADDR*)&dwAddress);
-
간단하게 네트웍 자체 연결이 되어 있는지 여부 체크
- private bool _networkCheck()
{
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
return true;
else
return false;
}
-
특정 서버(IP) 연결 여부를 체크: 링크 : msdn - Ping 클래스(System.Net.NetworkInformation)
public bool Connect(string ip, int port)
{
try
{
//IP Address 할당
this.ipAddress = IPAddress.Parse(ip);
//TCP Client 선언
this.tcpClient = new TcpClient(AddressFamily.InterNetwork);
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(this.ipAddress, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
// Ping 성공시 Connect 연결 시도
this.tcpClient.NoDelay = true;
this.tcpClient.Connect(ipAddress, port);
this.ntwStream = tcpClient.GetStream();
}
else
{
// Ping 실패시 강제 Exception
throw new Exception();
}
return true;
}
catch (Exception ex)
{
//MessageBox.Show("Connect Fail... : " + ex);
return false;
}
}
{
try
{
//IP Address 할당
this.ipAddress = IPAddress.Parse(ip);
//TCP Client 선언
this.tcpClient = new TcpClient(AddressFamily.InterNetwork);
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(this.ipAddress, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
// Ping 성공시 Connect 연결 시도
this.tcpClient.NoDelay = true;
this.tcpClient.Connect(ipAddress, port);
this.ntwStream = tcpClient.GetStream();
}
else
{
// Ping 실패시 강제 Exception
throw new Exception();
}
return true;
}
catch (Exception ex)
{
//MessageBox.Show("Connect Fail... : " + ex);
return false;
}
}