---
title: try_ip_as_binary
description: "try\\_ip\\_as\\_binary function in PySpark: Returns the canonical binary representation of an IP address or CIDR block. Returns `None` instead of raising an error if the input is invalid."
canonical_url: https://docs.databricks.com/gcp/en/pyspark/reference/functions/try_ip_as_binary
---

# try\_ip\_as\_binary

**Applies to:** ![check marked yes](https://docs.databricks.com/gcp/en/images/icons/check.png) Databricks Runtime 18.2 and above

> [!NOTE]
> **Beta**
>
> This feature is in [Beta](https://docs.databricks.com/gcp/en/release-notes/release-types.md).

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](https://docs.databricks.com/gcp/en/sql/language-manual/functions/try_ip_as_binary.md).

## Syntax

```python
from pyspark.databricks.sql import functions as dbf

dbf.try_ip_as_binary(col=<col>)
```

## Parameters

| Parameter | Type                          | Description                                                                       |
| --------- | ----------------------------- | --------------------------------------------------------------------------------- |
| `col`     | `pyspark.sql.Column` or `str` | 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)]
```
