Pages

19 thg 12, 2010

Lấy địa chỉ IP trong lập trình bằng một số ngôn ngữ thông dụng

Xin chào các bạn,

Đối với các lập trình viên ít nhất một lần cũng phải có nhu cầu lấy địa chỉ IP (Internet Protocol) cho việc phát triển ứng dụng. Ví dụ để phục vụ cho việc ghi log truy cập, chống đăng nhập nhiều tài khoản cùng một IP, chặn truy cập thông qua IP,… Thông qua những đoạn mã tổng hợp dưới đây, tôi hy vọng nó sẽ hữu ích trong việc tra cứu của các bạn khi cần. Một số ngôn ngữ như là C#, Delphi, VB.NET, VB, C, Java, ASP.NET, PHP, ASP.

Lấy địa chỉ IP

Lấy địa chỉ IP rất có ích trong phát triển ứng dụng (thường là Web)

1. C#

using System;
using System.Net;

namespace GetIPCS
{
///
/// Gets IP addresses of the local machine
///
class classGetIPCS
{
///
/// Gets IP addresses of the local machine
///
[STAThread]
static void Main(string[] args)
{
// Get host name
String strHostName = Dns.GetHostName();
Console.WriteLine("Host Name: " + strHostName);

// Find host by name
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

// Enumerate IP addresses
int nIP = 0;
foreach(IPAddress ipaddress in iphostentry.AddressList)
{
Console.WriteLine("IP #" + ++nIP + ": " +
ipaddress.ToString());
}
}
}
}

2. Delphi

uses  Winsock;

function getIPs: Tstrings;
type
TaPInAddr = array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
Buffer: array[0..63] of Char;
I: Integer;
GInitData: TWSAData;
begin
WSAStartup($101, GInitData);
Result := TstringList.Create;
Result.Clear;
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
I := 0;
while pPtr^[I] <> nil do
begin
Result.Add(inet_ntoa(pptr^[I]^));
Inc(I);
end;
WSACleanup;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(GetIps.text);
end;

3. VB.NET

Private Sub IPAddress()
'To get local address
Dim LocalHostName As String
Dim i As Integer
LocalHostName = Dns.GetHostName()
Dim ipEnter As IPHostEntry = Dns.GetHostByName(LocalHostName)
Dim IpAdd() As IPAddress = ipEnter.AddressList
For i = 0 To IpAdd.GetUpperBound(0)
Next
End Sub

4. VB

Private Declare Function GetIpAddrTable_API Lib "IpHlpApi" Alias "GetIpAddrTable" (pIPAddrTable As Any, pdwSize As Long, ByVal bOrder As Long) As Long

' Returns an array with the local IP addresses (as strings).
' Author: Christian d'Heureuse, www.source-code.biz
Public Function GetIpAddrTable()
Dim Buf(0 To 511) As Byte
Dim BufSize As Long: BufSize = UBound(Buf) + 1
Dim rc As Long
rc = GetIpAddrTable_API(Buf(0), BufSize, 1)
If rc <> 0 Then Err.Raise vbObjectError, , "GetIpAddrTable failed with return value " & rc
Dim NrOfEntries As Integer: NrOfEntries = Buf(1) * 256 + Buf(0)
If NrOfEntries = 0 Then GetIpAddrTable = Array(): Exit Function
ReDim IpAddrs(0 To NrOfEntries - 1) As String
Dim i As Integer
For i = 0 To NrOfEntries - 1
Dim j As Integer, s As String: s = ""
For j = 0 To 3: s = s & IIf(j > 0, ".", "") & Buf(4 + i * 24 + j): Next
IpAddrs(i) = s
Next
GetIpAddrTable = IpAddrs
End Function

' Test program for GetIpAddrTable.
Public Sub Test()
Dim IpAddrs
IpAddrs = GetIpAddrTable
Debug.Print "Nr of IP addresses: " & UBound(IpAddrs) - LBound(IpAddrs) + 1
Dim i As Integer
For i = LBound(IpAddrs) To UBound(IpAddrs)
Debug.Print IpAddrs(i)
Next
End Sub

5. C

// Borland C++ 5.0: bcc32.cpp getlocalip.cpp
// Visual C++ 5.0: cl getlocalip.cpp wsock32.lib
//
// This sample program is hereby placed in the public domain.

#include
#include

int doit(int, char **)
{
char ac[80];
if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) {
cerr < < "Error " << WSAGetLastError() <<
" when getting local host name." << endl;
return 1;
}
cout << "Host name is " << ac << "." << endl;

struct hostent *phe = gethostbyname(ac);
if (phe == 0) {
cerr << "Yow! Bad host lookup." << i =" 0;">h_addr_list != 0; ++i) {
struct in_addr addr;
memcpy(&addr, phe->h_addr_list, sizeof(struct in_addr));
cout < < "Address " << i << ": " << inet_ntoa(addr) << endl;
}

return 0;
}

int main(int argc, char *argv[])
{
WSAData wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
return 255;
}

int retval = doit(argc, argv);

WSACleanup();

return retval;
}
}

6. Java

import java.net.*;
import java.io.*;

public class GetIPAddress
{
public static void main(String [] args)
{
try
{
InetAddress thisIp =InetAddress.getLocalHost();
System.out.println("IP:"+thisIp.getHostAddress());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

7. ASP.NET

string ip;
ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR");
if(ip==string.Empty)
{
ip=Request.ServerVariables("REMOTE_ADDR");
}

8. PHP

$ip=$_SERVER['REMOTE_ADDR'];

9. ASP

<% Response.Write Request.ServerVariables("REMOTE_ADDR") %>

Thật đơn giản để sử dụng đúng không nào :) Chúc vui !

0 nhận xét:

Đăng nhận xét

Powered By Blogger