Python Socket模組中的IP轉換函式

2021-08-29 04:05:24 字數 1859 閱讀 9906

python socket模組中包含一些有用ip轉換函式,說明如下:

socket.ntohl(x)

// 類似於c語言的ntohl(x)

socket.ntohs(x)

// 類似於c語言的ntohs(x)

socket.htonl(x)

// 類似於c語言的htonl(x)

socket.htons(x)

// 類似於c語言的htons(x)

socket.inet_aton(ip_string)

// 依賴於inet_aton的c實現

socket.inet_ntoa(packed_ip)
socket.inet_pton(address_family,ip_string)
socket.inet_ntop(address_family,packed_ip)
import socket

import struct

socket.inet_aton(

"10.10.58.64"

)

b'\n\n:@'
struct.unpack(

"i",socket.inet_aton(

"10.10.58.64"

))

(1077545482,)
socket.ntohl(struct.unpack(

"i",socket.inet_aton(

"10.10.58.64"))

[0])

168442432
逆過程。

socket.htonl(

168442432

)

1077545482
struct.pack(

"i", socket.htonl(

168442432

))

b'\n\n:@'
socket.inet_ntoa(struct.pack(

"i", socket.htonl(

168442432))

)

'10.10.58.64'
def

ip2int

(ip_string)

:return struct.unpack(

"!i"

,socket.inet_aton(ip_string))[

0]

ip2int(

"10.10.58.64"

)

168442432
def

int2ip

(ip)

:return socket.inet_ntoa(struct.pack(

"!i"

,ip)

)

int2ip(

168442432

)

'10.10.58.64'

Python socket模組應用

socket 本文記錄了一些socket模組的簡單應用,對於具體原理還沒來得及深究。利用socket模組進行埠連線驗證和掃瞄 在linux中常用nc命令來進行遠端埠是否開放的驗證。但是這個命令並不是系統自帶的,所以還比較麻煩。如果利用python自帶的socket模組就可以比較自由地進行埠驗證了。是...

Python Socket模組中的IP轉換函式

python socket模組中包含一些有用ip轉換函式,說明如下 socket.ntohl x 類似於c語言的ntohl x 把32位正整數從網路序轉換成主機位元組序。socket.ntohs x 類似於c語言的ntohs x 把16位正整數從網路序轉換成主機位元組序。socket.htonl x...

python socket 函式 模組

import socket socket 函式 1,語法格式 socket.socket family type proto family 套接字家族可以使af unix或者af inet type 套接字型別可以根據是tcp連線和udp連線分為sock stream或sock dgram prot...