github.com/pion/dtls/v2@v2.2.12/examples/dial/selfsign/main.go (about)

     1  // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
     2  // SPDX-License-Identifier: MIT
     3  
     4  // Package main implements a DTLS client using self-signed certificates.
     5  package main
     6  
     7  import (
     8  	"context"
     9  	"crypto/tls"
    10  	"fmt"
    11  	"net"
    12  	"time"
    13  
    14  	"github.com/pion/dtls/v2"
    15  	"github.com/pion/dtls/v2/examples/util"
    16  	"github.com/pion/dtls/v2/pkg/crypto/selfsign"
    17  )
    18  
    19  func main() {
    20  	// Prepare the IP to connect to
    21  	addr := &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 4444}
    22  
    23  	// Generate a certificate and private key to secure the connection
    24  	certificate, genErr := selfsign.GenerateSelfSigned()
    25  	util.Check(genErr)
    26  
    27  	//
    28  	// Everything below is the pion-DTLS API! Thanks for using it ❤️.
    29  	//
    30  
    31  	// Prepare the configuration of the DTLS connection
    32  	config := &dtls.Config{
    33  		Certificates:         []tls.Certificate{certificate},
    34  		InsecureSkipVerify:   true,
    35  		ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
    36  	}
    37  
    38  	// Connect to a DTLS server
    39  	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    40  	defer cancel()
    41  	dtlsConn, err := dtls.DialWithContext(ctx, "udp", addr, config)
    42  	util.Check(err)
    43  	defer func() {
    44  		util.Check(dtlsConn.Close())
    45  	}()
    46  
    47  	fmt.Println("Connected; type 'exit' to shutdown gracefully")
    48  
    49  	// Simulate a chat session
    50  	util.Chat(dtlsConn)
    51  }