Pythonでネットワーク

import socket

class MySocket:
    # self.sock
    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(\
              socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock
    def connect(self, host, port):
        self.sock.connect((host, port))

    def close(self):
        self.sock.close()
        
    def send(self, msg):
        msglen = len(msg)
        totalsent = 0
        while totalsent < msglen:
            sent = self.sock.send(msg[totalsent:])
            if sent == 0:
                raise RuntimeError, \
                "socket connection broken"
            totalsent = totalsent + sent

    def recv(self, msglen):
        msg = ''
        while len(msg) < msglen:
            chunk = self.sock.recv(msglen-len(msg))
            if chunk == '':
                raise RuntimeError, \
                    "socket connection broken"
            msg = msg + chunk
        return msg

    def createServerSocket(self, port):
        #create an INET, STREAMing socket
        self.server_sock = socket.socket(
        socket.AF_INET, socket.SOCK_STREAM)        
        self.sock.bind((socket.gethostname(), port))
        self.sock.listen(5)


#class MyServer (MySocket):
#
#    def accept_test(self):
#        (clientsocket, address) = self.sock.accept()
#        ss = MySocket(clientsocket)
#        while True:
#            print ss.recv(100)
#
#
#server = MyServer()
#server.createServerSocket(23456)
#server.accept_test()
##server.

 

  • hostnameを取得。
    socket.gethostbyaddr(socket.gethostname())