+ -
当前位置:首页 → 问答吧 → python 通过网络发送数据

python 通过网络发送数据

时间:2011-03-06

来源:互联网

现在这样的,我想将一串字符串发送到局域网里另一台机器的一个端口上
如 data='2929A3002E463C485A11030609015003555852113283370000460199F800003DFFFF5F00001E0000000000000006010200003D0D'
 将这个字符串发送到192.168.0.12的8888端口上(udp),希望大家能够指点下,谢谢

作者: nothingsss   发布时间: 2011-03-06

http://pleac.sourceforge.net/pleac_python/sockets.html
Setting Up a UDP Client


import socket
# Set up a UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# send 
MSG = 'Hello'
HOSTNAME = '127.0.0.1'
PORTNO = 10000
s.connect((HOSTNAME, PORTNO))
if len(MSG) != s.send(MSG):
  # where to get error message "$!".
  print "cannot send to %s(%d):" % (HOSTNAME,PORTNO)
  raise SystemExit(1)
MAXLEN = 1024
(data,addr) = s.recvfrom(MAXLEN)
s.close()
print '%s(%d) said "%s"' % (addr[0],addr[1], data)

# download the following standalone program
#!/usr/bin/python
# clockdrift - compare another system's clock with this one

import socket
import struct
import sys
import time

if len(sys.argv)>1:
  him = sys.argv[1]
else:
  him = '127.1'

SECS_of_70_YEARS = 2208988800

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((him,socket.getservbyname('time','udp')))
s.send('')
(ptime, src) = s.recvfrom(4)
host = socket.gethostbyaddr(src[0])
delta = struct.unpack("!L", ptime)[0] - SECS_of_70_YEARS - time.time()
print "Clock on %s is %d seconds ahead of this one." % (host[0], delta)

作者: masterz   发布时间: 2011-03-06