Đố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.
1. Trong C# Code :
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
Code:
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
Code:
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
5. Trong C
Code:
// 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." << endl; return 1; } for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[i], 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
Code:
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
Code:
string ip;
ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR");
if(ip==string.Empty)
{
ip=Request.ServerVariables("REMOTE_ADDR");
}
8. PHP
PHP Code:
$ip=$_SERVER[‘REMOTE_ADDR’];
9. ASP
Code:
< % Response .Write
Request .ServerVariables
( "REMOTE_ADDR"
) % > Thật đơn giản để sử dụng đúng không nào , Chúc vui !
THAM KHẢO THÊM CÁC SẢN PHẨM HOT NHẤT HIỆN NAY Giày Cafe SHOEX Hạ Khang Đường - Ổn định đường huyết Saffron Extra White Cốc Nguyệt San BEUCUP Maxi White Fysoline - Nước muối sinh lý dành cho bé sơ sinh và trẻ nhỏ Mặt nạ thon mặt Vline Finava - Tinh chất vàng sáng da, trị nám ngăn ngừa lão hoá Trị Mụn Caryophy Rong Nho Sabudo Son YUMEISAKURA Máy Khử Mùi MARKEL Orlavi - Làm mờ sẹo Dottorprimo - Trị các vết sẹo nặng ZEN - Sản phẩm giúp hỗ trợ giảm căng thẳng Nồi Chiên Không Dầu COSORI Nồi Chiên Không Dầu LOTTE Dưỡng Trắng RealWhite Máy rửa mặt Pebble Lisa Dầu Gội Nature Quen - Sao Thái Dương