本文整理汇总了Golang中net.IPv4函数的典型用法代码示例。如果您正苦于以下问题:Golang IPv4函数的具体用法?Golang IPv4怎么用?Golang IPv4使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IPv4函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestParseInterfaceStanzaStaticPostUp
func TestParseInterfaceStanzaStaticPostUp(t *testing.T) {
options := []string{
"address 192.168.1.100",
"netmask 255.255.255.0",
"post-up route add gw 192.168.1.1 -net 192.168.1.0 netmask 255.255.255.0",
}
expect := []route{
{
destination: net.IPNet{
IP: net.IPv4(192, 168, 1, 0),
Mask: net.IPv4Mask(255, 255, 255, 0),
},
gateway: net.IPv4(192, 168, 1, 1),
},
}
iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, options)
if err != nil {
t.FailNow()
}
static, ok := iface.configMethod.(configMethodStatic)
if !ok {
t.FailNow()
}
if !reflect.DeepEqual(static.routes, expect) {
t.FailNow()
}
}
示例2: newGogopbLog
func newGogopbLog(record *gogopb.Log) {
record.Timestamp = time.Now().UnixNano()
record.ZoneId = 123456
record.ZonePlan = gogopb.ZonePlan_FREE
record.Http = gogopb.HTTP{
Protocol: gogopb.HTTP_HTTP11,
Status: 200,
HostStatus: 503,
UpStatus: 520,
Method: gogopb.HTTP_GET,
ContentType: "text/html",
UserAgent: userAgent,
Referer: "https://www.cloudflare.com/",
RequestURI: "/cdn-cgi/trace",
}
record.Origin = gogopb.Origin{
Ip: gogopb.IP(net.IPv4(1, 2, 3, 4).To4()),
Port: 8080,
Hostname: "www.example.com",
Protocol: gogopb.Origin_HTTPS,
}
record.Country = gogopb.Country_US
record.CacheStatus = gogopb.CacheStatus_HIT
record.ServerIp = gogopb.IP(net.IPv4(192, 168, 1, 1).To4())
record.ServerName = "metal.cloudflare.com"
record.RemoteIp = gogopb.IP(net.IPv4(10, 1, 2, 3).To4())
record.BytesDlv = 123456
record.RayId = "10c73629cce30078-LAX"
}
示例3: ParseHeader
// ParseHeader parses b as an IPv4 header.
func ParseHeader(b []byte) (*Header, error) {
if len(b) < HeaderLen {
return nil, errHeaderTooShort
}
hdrlen := (int(b[0]) & 0x0f) << 2
if hdrlen > len(b) {
return nil, errBufferTooShort
}
h := &Header{}
h.Version = int(b[0] >> 4)
h.Len = hdrlen
h.TOS = int(b[posTOS])
if supportsNewIPInput {
h.TotalLen = int(b[posTotalLen])<<8 | int(b[posTotalLen+1])
h.FragOff = int(b[posFragOff])<<8 | int(b[posFragOff+1])
} else {
h.TotalLen = int(*(*uint16)(unsafe.Pointer(&b[posTotalLen : posTotalLen+1][0])))
h.TotalLen += hdrlen
h.FragOff = int(*(*uint16)(unsafe.Pointer(&b[posFragOff : posFragOff+1][0])))
}
h.ID = int(b[posID])<<8 | int(b[posID+1])
h.TTL = int(b[posTTL])
h.Protocol = int(b[posProtocol])
h.Checksum = int(b[posChecksum])<<8 | int(b[posChecksum+1])
h.Src = net.IPv4(b[posSrc], b[posSrc+1], b[posSrc+2], b[posSrc+3])
h.Dst = net.IPv4(b[posDst], b[posDst+1], b[posDst+2], b[posDst+3])
if hdrlen-HeaderLen > 0 {
h.Options = make([]byte, hdrlen-HeaderLen)
copy(h.Options, b[HeaderLen:])
}
return h, nil
}
示例4: TestStickyLoadBalanaceWorksWithMultipleEndpointsStickyNone
func TestStickyLoadBalanaceWorksWithMultipleEndpointsStickyNone(t *testing.T) {
client1 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}
client2 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 2), Port: 0}
client3 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 3), Port: 0}
loadBalancer := NewLoadBalancerRR()
service := ServicePortName{types.NamespacedName{"testnamespace", "foo"}, ""}
endpoint, err := loadBalancer.NextEndpoint(service, nil)
if err == nil || len(endpoint) != 0 {
t.Errorf("Didn't fail with non-existent service")
}
loadBalancer.NewService(service, api.AffinityTypeNone, 0)
endpoints := make([]api.Endpoints, 1)
endpoints[0] = api.Endpoints{
ObjectMeta: api.ObjectMeta{Name: service.Name, Namespace: service.Namespace},
Subsets: []api.EndpointSubset{
{
Addresses: []api.EndpointAddress{{IP: "endpoint"}},
Ports: []api.EndpointPort{{Port: 1}, {Port: 2}, {Port: 3}},
},
},
}
loadBalancer.OnUpdate(endpoints)
shuffledEndpoints := loadBalancer.services[service].endpoints
expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client1)
expectEndpoint(t, loadBalancer, service, shuffledEndpoints[2], client2)
expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client2)
expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client3)
expectEndpoint(t, loadBalancer, service, shuffledEndpoints[2], client3)
expectEndpoint(t, loadBalancer, service, shuffledEndpoints[0], client1)
expectEndpoint(t, loadBalancer, service, shuffledEndpoints[1], client1)
}
示例5: testIPs
func testIPs() (output []net.IP) {
output = append(output, net.IPv4(127, 0, 1, 2))
output = append(output, net.IPv4(128, 0, 1, 2))
output = append(output, net.IPv4(129, 0, 1, 2))
output = append(output, net.IPv4(130, 0, 1, 2))
return output
}
示例6: TestUDPWriteError
func TestUDPWriteError(t *testing.T) {
frontendAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}
// Hopefully, this port will be free: */
backendAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 25587}
proxy, err := NewProxy(frontendAddr, backendAddr)
if err != nil {
t.Fatal(err)
}
defer proxy.Close()
go proxy.Run()
client, err := net.Dial("udp", "127.0.0.1:25587")
if err != nil {
t.Fatalf("Can't connect to the proxy: %v", err)
}
defer client.Close()
// Make sure the proxy doesn't stop when there is no actual backend:
client.Write(testBuf)
client.Write(testBuf)
backend := NewEchoServer(t, "udp", "127.0.0.1:25587")
defer backend.Close()
backend.Run()
client.SetDeadline(time.Now().Add(10 * time.Second))
if _, err = client.Write(testBuf); err != nil {
t.Fatal(err)
}
recvBuf := make([]byte, testBufSize)
if _, err = client.Read(recvBuf); err != nil {
t.Fatal(err)
}
if !bytes.Equal(testBuf, recvBuf) {
t.Fatal(fmt.Errorf("Expected [%v] but got [%v]", testBuf, recvBuf))
}
}
示例7: ReadMessage
func ReadMessage(c *net.UDPConn) (msg *Message, src net.Addr, err os.Error) {
buff := make([]byte, DHCP_MAX_LEN)
//log.Printf("Waiting for read")
n, src, err := c.ReadFromUDP(buff)
if err != nil {
return
}
if n < DHCP_MIN_LEN {
err = os.NewError("Invalid DHCP messge received (too small)")
return
}
buff = buff[0:n]
msg = &Message{
Operation: buff[0],
HardwareType: buff[1],
HardwareLen: buff[2],
Hops: buff[3],
Xid: binary.LittleEndian.Uint32(buff[4:8]),
Secs: binary.LittleEndian.Uint16(buff[8:10]),
Flags: binary.LittleEndian.Uint16(buff[10:12]),
ClientIP: net.IPv4(buff[12], buff[13], buff[14], buff[15]),
YourIP: net.IPv4(buff[16], buff[17], buff[18], buff[19]),
ServerIP: net.IPv4(buff[20], buff[21], buff[22], buff[23]),
GatewayIP: net.IPv4(buff[24], buff[25], buff[26], buff[27]),
}
copy(msg.ClientHWAddr[0:16], buff[28:44])
// We skip the magic bytes and assume for now.
msg.Options, err = ParseOptions(buff[DHCP_MIN_LEN+4:])
//log.Printf("Parsed %d options.", len(msg.Options))
// TODO: Handle Option 52 extensions.
return
}
示例8: TestFetchHypervisors
func TestFetchHypervisors(t *testing.T) {
// Setup
f := NewFetcher("http://127.0.0.1:4001")
defer testhelper.Cleanup(f.etcdClient)
// Create supporting objects
n, err := testhelper.NewNetwork(f.context)
h.Ok(t, err)
s, err := testhelper.NewSubnet(f.context, "10.10.10.0/24", net.IPv4(10, 10, 10, 1), net.IPv4(10, 10, 10, 10), net.IPv4(10, 10, 10, 250), n)
h.Ok(t, err)
// Create two hypervisors
h1, err := testhelper.NewHypervisor(f.context, "de:ad:be:ef:7f:21", net.IPv4(192, 168, 100, 200), net.IPv4(192, 168, 100, 1), net.IPv4(255, 255, 255, 0), "br0", s)
h.Ok(t, err)
h2, err := testhelper.NewHypervisor(f.context, "de:ad:be:ef:7f:23", net.IPv4(192, 168, 100, 203), net.IPv4(192, 168, 100, 1), net.IPv4(255, 255, 255, 0), "br0", s)
h.Ok(t, err)
// Fetch and make sure they're present
hvs, err := f.Hypervisors()
h.Ok(t, err)
if _, ok := hvs[h1.ID]; !ok {
t.Error("Hypervisor #1 is missing from list")
}
h.Equals(t, hvs[h1.ID].MAC.String(), "de:ad:be:ef:7f:21")
if _, ok := hvs[h2.ID]; !ok {
t.Error("Hypervisor #2 is missing from list")
}
h.Equals(t, hvs[h2.ID].MAC.String(), "de:ad:be:ef:7f:23")
}
示例9: TestFetchSubnets
func TestFetchSubnets(t *testing.T) {
// Setup
f := NewFetcher("http://127.0.0.1:4001")
defer testhelper.Cleanup(f.etcdClient)
// Create supporting object
n, err := testhelper.NewNetwork(f.context)
h.Ok(t, err)
// Create two subnets
s1, err := testhelper.NewSubnet(f.context, "10.10.10.0/24", net.IPv4(10, 10, 10, 1), net.IPv4(10, 10, 10, 10), net.IPv4(10, 10, 10, 250), n)
h.Ok(t, err)
s2, err := testhelper.NewSubnet(f.context, "12.12.12.0/24", net.IPv4(12, 12, 12, 1), net.IPv4(12, 12, 12, 12), net.IPv4(12, 12, 12, 250), n)
h.Ok(t, err)
// Fetch and make sure they're present
ss, err := f.Subnets()
h.Ok(t, err)
if _, ok := ss[s1.ID]; !ok {
t.Error("Subnet #1 is missing from list")
}
h.Equals(t, ss[s1.ID].CIDR.String(), "10.10.10.0/24")
if _, ok := ss[s2.ID]; !ok {
t.Error("Subnet #2 is missing from list")
}
h.Equals(t, ss[s2.ID].CIDR.String(), "12.12.12.0/24")
}
示例10: main
func main() {
flag.Parse()
lwipv6.Initialize(0)
defer lwipv6.Finish()
intf := lwipv6.CreateInterface(lwipv6.IF_VDE, *socket, 0)
if intf == nil {
log.Fatalln("Interface setup failed to:", *socket)
}
ip := net.IPv4(192, 168, 123, 2)
mask := net.IPMask(net.IPv4(255, 255, 255, 0))
if intf.AddAddress(net.IPNet{ip, mask}) != 0 {
log.Fatalln("Adding address failed.")
}
if intf.IfUp(0) != 0 {
log.Fatalln("Failed bringing interface up")
}
fmt.Println("Interface up successfully! Press any key to exit.")
var input string
fmt.Scanln(&input)
fmt.Println("Exiting.")
}
示例11: TestStickyLoadBalanaceWorksWithMultipleEndpointsStickyNone
func TestStickyLoadBalanaceWorksWithMultipleEndpointsStickyNone(t *testing.T) {
client1 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}
client2 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 2), Port: 0}
client3 := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 3), Port: 0}
loadBalancer := NewLoadBalancerRR()
endpoint, err := loadBalancer.NextEndpoint("foo", nil)
if err == nil || len(endpoint) != 0 {
t.Errorf("Didn't fail with non-existent service")
}
loadBalancer.NewService("foo", api.AffinityTypeNone, 0)
endpoints := make([]api.Endpoints, 1)
endpoints[0] = api.Endpoints{
ObjectMeta: api.ObjectMeta{Name: "foo"},
Endpoints: []string{"endpoint:1", "endpoint:2", "endpoint:3"},
}
loadBalancer.OnUpdate(endpoints)
expectEndpoint(t, loadBalancer, "foo", "endpoint:1", client1)
expectEndpoint(t, loadBalancer, "foo", "endpoint:2", client1)
expectEndpoint(t, loadBalancer, "foo", "endpoint:3", client2)
expectEndpoint(t, loadBalancer, "foo", "endpoint:1", client2)
expectEndpoint(t, loadBalancer, "foo", "endpoint:2", client3)
expectEndpoint(t, loadBalancer, "foo", "endpoint:3", client3)
expectEndpoint(t, loadBalancer, "foo", "endpoint:1", client1)
expectEndpoint(t, loadBalancer, "foo", "endpoint:2", client1)
}
示例12: TestMachineAddresses
func (s *MachinerSuite) TestMachineAddresses(c *gc.C) {
s.PatchValue(machiner.InterfaceAddrs, func() ([]net.Addr, error) {
addrs := []net.Addr{
&net.IPAddr{IP: net.IPv4(10, 0, 0, 1)},
&net.IPAddr{IP: net.IPv4(127, 0, 0, 1)},
&net.IPAddr{IP: net.IPv6loopback},
&net.UnixAddr{}, // not IP, ignored
&net.IPNet{IP: net.ParseIP("2001:db8::1")},
&net.IPAddr{IP: net.IPv4(169, 254, 1, 20)}, // LinkLocal Ignored
&net.IPNet{IP: net.ParseIP("fe80::1")}, // LinkLocal Ignored
}
return addrs, nil
})
mr := s.makeMachiner()
defer worker.Stop(mr)
c.Assert(s.machine.Destroy(), gc.IsNil)
s.State.StartSync()
c.Assert(mr.Wait(), gc.Equals, worker.ErrTerminateAgent)
c.Assert(s.machine.Refresh(), gc.IsNil)
c.Assert(s.machine.MachineAddresses(), jc.DeepEquals, []network.Address{
network.NewAddress("2001:db8::1", network.ScopeUnknown),
network.NewAddress("::1", network.ScopeMachineLocal),
network.NewAddress("10.0.0.1", network.ScopeCloudLocal),
network.NewAddress("127.0.0.1", network.ScopeMachineLocal),
})
}
示例13: TestInitiateHandshakes
func TestInitiateHandshakes(t *testing.T) {
Convey("Sends out handshake request to every IP in list", t, func() {
s := NewBTService(port, []byte(peerIDRemote))
mc := NewMockConnectionFetcher()
s.ConnectionFetcher = mc
s.AddHash(hash)
_ = s.StartListening()
// TODO: check that peer data is saved within service data structure
peers := make([]structure.Peer, 2)
peers[0] = structure.Peer{IP: net.IPv4(192, 168, 1, 1), Port: 55556}
peers[1] = structure.Peer{IP: net.IPv4(192, 168, 1, 2), Port: 55557}
s.InitiateHandshakes(hash, peers)
for _, p := range peers {
c0 := mc.Conns[p.AddrString()].Conn.(*MockConnection)
hs, err := structure.ReadHandshake(bytes.NewReader(<-c0.ReceiveBytesChan))
So(hs, ShouldNotBeNil)
So(err, ShouldBeNil)
hs, _ = structure.NewHandshake(hash, []byte(peerIDClient))
c0.SendMessage(hs)
}
time.Sleep(time.Millisecond)
So(len(s.Peers), ShouldEqual, len(peers))
_ = s.StopListening()
time.Sleep(time.Millisecond)
So(s.Listening, ShouldBeFalse)
})
}
示例14: BenchmarkSummarizeIPv4
func BenchmarkSummarizeIPv4(b *testing.B) {
fip, lip := net.IPv4(172, 16, 1, 1), net.IPv4(172, 16, 255, 255)
for i := 0; i < b.N; i++ {
ipaddr.Summarize(fip, lip)
}
}
示例15: TestIcmpIsLocalIp
func TestIcmpIsLocalIp(t *testing.T) {
icmp := Icmp{localIps: []net.IP{net.IPv4(192, 168, 0, 1), net.IPv4(192, 168, 0, 2)}}
assert.True(t, icmp.isLocalIp(net.IPv4(127, 0, 0, 1)), "loopback IP")
assert.True(t, icmp.isLocalIp(net.IPv4(192, 168, 0, 1)), "local IP")
assert.False(t, icmp.isLocalIp(net.IPv4(10, 0, 0, 1)), "remote IP")
}