try_ip_as_binary
Applies to: Databricks Runtime 18.2 and above
Beta
This feature is in Beta. Workspace admins can control access to this feature from the Previews page. See Manage Databricks previews.
Returns the canonical binary representation of an IP address or CIDR block. Returns None instead of raising an error if the input is invalid.
For the corresponding SQL function, see try_ip_as_binary function.
Syntax
Python
from pyspark.databricks.sql import functions as dbf
dbf.try_ip_as_binary(col=<col>)
Parameters
Parameter | Type | Description |
|---|---|---|
|
| A STRING or BINARY value representing a valid IPv4 or IPv6 address or CIDR block. |
Examples
Example 1: Convert an IPv4 address to binary.
Python
from pyspark.databricks.sql import functions as dbf
from pyspark.sql.functions import hex
df = spark.createDataFrame([('192.168.1.1',)], ['ip'])
df.select(hex(dbf.try_ip_as_binary('ip')).alias('result')).collect()
Output
[Row(result='C0A80101')]
Example 2: Convert an IPv6 address to binary.
Python
from pyspark.databricks.sql import functions as dbf
from pyspark.sql.functions import hex
df = spark.createDataFrame([('2001:db8::1',)], ['ip'])
df.select(hex(dbf.try_ip_as_binary('ip')).alias('result')).collect()
Output
[Row(result='20010DB8000000000000000000000001')]
Example 3: Convert a CIDR block to binary.
Python
from pyspark.databricks.sql import functions as dbf
from pyspark.sql.functions import hex
df = spark.createDataFrame([('192.168.1.5/24',)], ['cidr'])
df.select(hex(dbf.try_ip_as_binary('cidr')).alias('result')).collect()
Output
[Row(result='C0A8010018')]
Example 4: Invalid input returns None.
Python
from pyspark.databricks.sql import functions as dbf
df = spark.createDataFrame([('invalid.ip',)], ['ip'])
df.select(dbf.try_ip_as_binary('ip').alias('result')).collect()
Output
[Row(result=None)]
Example 5: None input returns None.
Python
from pyspark.databricks.sql import functions as dbf
df = spark.createDataFrame([(None,)], 'ip: string')
df.select(dbf.try_ip_as_binary('ip').alias('result')).collect()
Output
[Row(result=None)]