1 # Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
2 # Copyright (C) 2014 YAMAMOTO Takashi <yamamoto at valinux co jp>
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
21 from ryu.lib import addrconv
24 system = platform.system()
43 _SIN_SIZE = 16 # sizeof(struct sockaddr_in)
45 _HDR_LEN = struct.calcsize(_HDR_FMT)
50 return struct.pack(_HDR_FMT, ss_len, af)
52 return struct.pack(_HDR_FMT, af)
55 def _pad_to(data, total_len):
56 pad_len = total_len - len(data)
57 return data + pad_len * '\0'
60 def sa_in4(addr, port=0):
61 data = struct.pack("!H4s", port, addrconv.ipv4.text_to_bin(addr))
62 hdr = _hdr(_SIN_SIZE, socket.AF_INET)
63 return _pad_to(hdr + data, _SIN_SIZE)
66 def sa_in6(addr, port=0, flowinfo=0, scope_id=0):
67 data = struct.pack("!HI16sI", port, flowinfo,
68 addrconv.ipv6.text_to_bin(addr), scope_id)
69 hdr = _hdr(_HDR_LEN + len(data), socket.AF_INET6)
74 return _pad_to(sa, _SS_MAXSIZE)